bitwise not operator

前端 未结 10 993
广开言路
广开言路 2021-01-30 16:24

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

10条回答
  •  醉话见心
    2021-01-30 17:07

    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"

提交回复
热议问题