Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bitwise not operator

Why bitwise operation (~0); prints -1 ? In binary , not 0 should be 1 . why ?

like image 497
Sawyer Avatar asked Mar 25 '10 06:03

Sawyer


People also ask

What is Bitwise NOT operator in C?

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.

How does Bitwise NOT operator work in Java?

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.

How Bitwise not works in Python?

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 .


2 Answers

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:

  • Two's complement
    • This is the system used by Java (among others) to represent signed numerical value in bits
  • JLS 15.15.5 Bitwise complement operator ~
    • "note that, in all cases, ~x equals (-x)-1"
like image 50
polygenelubricants Avatar answered Sep 25 '22 12:09

polygenelubricants


What you are actually saying is ~0x00000000 and that results in 0xFFFFFFFF. For a (signed) int in java, that means -1.

like image 35
LaZe Avatar answered Sep 23 '22 12:09

LaZe