Why bitwise operation (~0);
prints -1 ? In binary , not 0 should be 1 . why ?
It's binary inversion, and in second complement -1 is binary inversion of 0.
What you are actually saying is ~0x00000000 and that results in 0xFFFFFFFF. For a (signed) int in java, that means -1.
Because ~
is not binary inversion, it’s bitwise inversion. Binary inversion would be !
and can (in Java) only be applied to boolean values.
I think the real reason is that ~ is Two’s Complement.
Javascript designates the character tilde, ~, for the two’s complement, even though in most programming languages tilde represents a bit toggle for the one’s complement.
In standard binary encoding, 0 is all 0s, ~
is bitwise NOT. All 1s is (most often) -1 for signed integer types. So for a signed byte type:
0xFF = -1 // 1111 1111
0xFE = -2 // 1111 1110
...
0xF0 = -128 // 1000 0000
0x7F = 127 // 0111 1111
0x7E = 126 // 0111 1110
...
0x01 = 1 // 0000 0001
0x00 = 0 // 0000 0000
For 32 bit signed integer
~00000000000000000000000000000000=11111111111111111111111111111111
(which is -1)