Why bitwise operation (~0);
prints -1 ? In binary , not 0 should be 1 . why ?
You could imagine the first bit in a signed number to be -(2x -1) where x is the number of bits.
So, given an 8-bit number, the value of each bit (in left to right order) is:
-128 64 32 16 8 4 2 1
Now, in binary, 0 is obviously all 0s:
-128 64 32 16 8 4 2 1
0 0 0 0 0 0 0 0 0 = 0
And when you do the bitwise not ~
each of these 0s becomes a 1:
-128 64 32 16 8 4 2 1
~0 1 1 1 1 1 1 1 1
= -128+64+32+16+8+4+2+1 == -1
This is also helpful in understanding overflow:
-128 64 32 16 8 4 2 1
126 0 1 1 1 1 1 1 0 = 126
+1 0 1 1 1 1 1 1 1 = 127
+1 1 0 0 0 0 0 0 0 = -128 overflow!