What is the use of complementry operator in c?
The bitwise complement or one's complement operator (~) is used
to switch the state of all the bits in a value. Thus 1's become 0,
and 0's become 1.
One of its many uses is to unset individual bit(s) in a bitmap.
We do this with a bitwise AND of the bitmap and the bitwise
complement of the bit(s) we want to unset.
Original bitmap: 01011100
Bit to unset: 00000100 (e.g., bit 2 (bits are zero based from
right))
// Using one's complement and bitwise AND
~00000100 & 01011100
11111011 (one's complement of bit 2)
&
01011100 (original bitmap)
=
01011000 (original bitmap with bit 2 unset)
Note that this formula works even if bit 2 were already
unset:
11111011 (one's complement of bit 2)
&
01011000 (original bitmap, with bit 2 unset)
=
01011000 (original bitmap unchanged)