D
D
D_D-0_02015-12-25 01:28:22
Programming
D_D-0_0, 2015-12-25 01:28:22

Why is it necessary and possible to use bitwise negation (tilde) for unsigned numbers in C programming?

Why is it necessary and possible to use bitwise negation (tilde) for unsigned numbers in C programming?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
abcd0x00, 2015-12-25
@D_D-0_0

The most common use of bitwise negation is to keep the set bits intact during bitwise multiplication.
For example:
You have a variable with bit flags
0101 0011
There are 8 bits and each contains a flag: 0 - there is no flag, 1 - there is a flag.
Here you need to remove the most extreme flag on the right, because it means something in the program. (Like there was some file on the disk, and then it was erased and you need to mark it so that the program knows.)
To remove the rightmost flag, you need to turn
0101 0011
into
0101 0010
And how to do this?
You need to take the value of the variable, change it and save the result back.
To change it, we make a mask and bitwise multiply it by the original value (& operation).
That is, we need to execute
0101 0011
&
1111 1110
Then the rightmost flag will become zero, and the remaining flags will remain unaffected, since bitwise multiplication by 1 gives the same thing as it was there.
And here the main question arises: how to make this mask?
We can write it directly or get it using bitwise operations.
We take the number 1, it looks like
0000 0001
, apply the bitwise negation operation (operation ~)
1111 1110 to
it and see our mask.

O
Oleg Tsilyurik, 2015-12-25
@Olej

Is this a question from a pioneer?
In general, in programming, even when learning your 5th programming language, you need to forever abandon the question of why for any syntactic constructions? and wonder how?
Even if some construction strongly outrages you (goto) - just don't use it . ;-)
And "why in C programming is it necessary and possible to apply" ... the operation of integer addition?
The correct answer to such burning questions should be: for everything ;-)

P
Peter, 2015-12-25
@petermzg

For example, if your number is a mask, and you need to reset (set to zero) only the third bit, then you can apply like this ( ~4 & mask )

M
mamkaololosha, 2015-12-25
@mamkaololosha

Purely hypothetically, it could be anything at all.
habrahabr.ru/post/183462/#comment_6374890

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question