Why bitwise operation (~0);
prints -1 ? In binary , not 0 should be 1 . why ?
Binary One's Complement or Bitwise NOT operator (~) in C: The C compiler recognizes the Bitwise NOT with ~ operator. It takes only one operand and performs the inversion of all digits of it. It is a unary operator. The output of this operator will invert all the existing bits of that operand.
Bitwise Not or Complement operator simply means the negation of each bit of the input value. It takes only one integer and it's equivalent to the ! operator. This operator changes each binary digit of the integer, which means all 0 become 1 and all 1 become 0.
Python's bitwise NOT operator ~x inverts each bit from the binary representation of integer x so that 0 becomes 1 and 1 becomes 0. This is semantically the same as calculating ~x == -x-1 . For example, the bitwise NOT expression ~0 becomes -1 , ~9 becomes -10 , and ~32 becomes -33 .
You are actually quite close.
In binary , not 0 should be 1
Yes, this is absolutely correct when we're talking about one bit.
HOWEVER, an int
whose value is 0 is actually 32 bits of all zeroes! ~
inverts all 32 zeroes to 32 ones.
System.out.println(Integer.toBinaryString(~0)); // prints "11111111111111111111111111111111"
This is the two's complement representation of -1
.
Similarly:
System.out.println(Integer.toBinaryString(~1)); // prints "11111111111111111111111111111110"
That is, for a 32-bit unsigned int
in two's complement representation, ~1 == -2
.
Further reading:
~
~x
equals (-x)-1
"What you are actually saying is ~0x00000000 and that results in 0xFFFFFFFF. For a (signed) int in java, that means -1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With