Sunday, 17 April 2011

Binary representation of negative numbers in java : 2's complement

Negative numbers in Java are represented using 2's complement. As we know that integers in Java occupy 4 bytes so to understand how a negative integer (say -4) is represented internally in Java, we first need to find the binary equivalent of the positive value of the integer (in this case 4) and subsequently by finding the 2's complement of that binary representation.

Okay, so how do find 2's complement of a binary number? Simply by adding '1' to the 1's complement of that number. But, how to find 1's complement of a binary number then? Just by reverting the bits of the number i.e., changing 1s to 0s and 0s to 1s. An example may of of some help here.

Example
int i = -4;
...

Step #1: Binary Equivalent of the positive value (4 in this case)

0000 0000 0000 0000 0000 0000 0000 0100

Step #2: 1's complement of the binary rep of 4 by inverting the bits

1111 1111 1111 1111 1111 1111 1111 1011

Step #3: Finding 2's complement by adding 1 to the corresponding 1's complement

1111 1111 1111 1111 1111 1111 1111 1011
0000 0000 0000 0000 0000 0000 0000 0001
---------------------------------------
1111 1111 1111 1111 1111 1111 1111 1100

Thus, we see that integer -4 is represented by the binary sequence (1111 1111 1111 1111 1111 1111 1111 1100) in Java.

Once we have an understanding of how the numbers are represented internally, bit-level manipulation becomes easily understandable, which otherwise is obviously one of the hardest things in Java (or any other language supporting that) to visualize.

No comments:

Post a Comment