Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary presentation of negative integer in Java

Tags:

java

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

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

And as I understand binary presentation of -5 should be like 10000000.00000000.00000000.00000101.

But output is 11111111.11111111.11111111.11111011.

I have 2 question:

1) Why here is so much 1 bits.

2) What I really cant understand it last 3 bits 011. It looks like 3. Even +1 or -1 it'll be 100 or 010

Thanks

like image 420
Petr Shypila Avatar asked Oct 11 '14 14:10

Petr Shypila


2 Answers

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.

like image 136
paxdiablo Avatar answered Nov 02 '22 23:11

paxdiablo


And as I understand binary presentation of -5 should be like 10000000.00000000.00000000.00000101.

That would be right if Java used a Sign and Magnitude representation for integers. However, Java uses Two's Complement representation, so the rest of the bits are changed in accordance with the rules of that representation.

The idea behind two's complement representation is that when you add a number in such representation to another value dropping the extra bit on the most significant end, the result would be as if you subtracted a positive number of the same magnitude.

You can illustrate this with decimal numbers. In a two-digit representation, the value of 99 would behave like -1, 98 would be like -2, 97 like -3, and so on. For example, if you drop the top digit in 23 + 99 = [1]22, so 99 behaved like -1. 23 + 98 = [1]21, so 98 behaved like -2.

This works the same way with two's complement representation of binary numbers, except you would drop the extra bit at the top.

like image 40
Sergey Kalinichenko Avatar answered Nov 02 '22 22:11

Sergey Kalinichenko