bitwise not operator

前端 未结 10 986
广开言路
广开言路 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"
    0 讨论(0)
  • 2021-01-30 17:08

    0 here is not a bit. It is a byte (at least; or more) - 00000000. Using bitwise or we will have 11111111. It is -1 as signed integer...

    0 讨论(0)
  • 2021-01-30 17:11

    ~ is a bitwise operator.

    ~0 = 1 which is -1 in 2's complement form  
    

    http://en.wikipedia.org/wiki/Two's_complement

    Some numbers in two's complement form and their bit-wise not ~ (just below them):

    0 1 1 1 1 1 1 1 = 127
    1 0 0 0 0 0 0 0 = −128

    0 1 1 1 1 1 1 0 = 126
    1 0 0 0 0 0 0 1 = −127

    1 1 1 1 1 1 1 1 = −1
    0 0 0 0 0 0 0 0 = 0

    1 1 1 1 1 1 1 0 = −2
    0 0 0 0 0 0 0 1 = 1

    1 0 0 0 0 0 0 1 = −127
    0 1 1 1 1 1 1 0 = 126

    1 0 0 0 0 0 0 0 = −128
    0 1 1 1 1 1 1 1 = 127

    0 讨论(0)
  • 2021-01-30 17:13

    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!
    
    0 讨论(0)
提交回复
热议问题