Binary presentation of negative integer in Java

后端 未结 5 2022
予麋鹿
予麋鹿 2020-12-03 22:30

Please, help me to understand binary presentation of negative integers.

For example we have 5. Binary presentation of 5 is 00000000.00000000.00000000.00000101

5条回答
  •  广开言路
    2020-12-03 23:17

    Your understanding of what those negative numbers should look like is flawed. Java uses two's complement for negative numbers and the basic rule is to take the positive, invert all bits then add one. That gets you the negative.

    Hence five is, as you state:

    0000...00000101
    

    Inverting that gives you:

    1111...11111010
    

    Then adding one gives:

    1111...11111011
    

    The bit pattern you have shown for -5 is what's called sign/magnitude, where you negate a number simply by flipping the leftmost bit. That's allowed in C implementations as one of the three possibilities(a), but Java uses two's complement only (for its negative integers).


    (a) But keep in mind there are current efforts in both C and C++ to remove the other two encoding types and allow only two's complement.

提交回复
热议问题