Binary presentation of negative integer in Java

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.

Leave a Comment