2’s complement representation in Java
May 5, 2012

Hello to everyone,

after a long time here is another post from a geek dad. I’d like to talk about how negative numbers are represented in Java so as to make bit manipulation easier. Let’s take into account integer data types (i’m not talking about Integer class, but about primitive types); from Java tutorial

integer primitive type is defines as “32-bit signed two’s complement integer”, which could have values from -2147483648 to 2147483647 (limits included). Since int is 4bytes (32 bits) you can calculate these values easily:

  1. Upper limit =  \frac{2^{32}}{2}- 1=2147483647
  2. Lower limit = -\frac{2^{32}}{2}=-2147483648
  3. General formula for non negative upper limit  \frac{2^{n}}{2}- 1  where n is the number of bits.
  4. General formula for negative lower limit  -\frac{2^{n}}{2}1  where n is the number of bits.
  5. If the primitive is unsigned the lower limit is 0, while the upper limit becomes {2^{n}}- 1

Ok, up to know it’s pretty simple, but what about 2’s complement? Or what 2’s complement is?

Wikipedia defines it as “The two’s complement of a binary number is defined as the value obtained by subtracting the number from a large power of two (specifically, from 2N for an N-bit two’s complement). The two’s complement of the number  behaves like the negative of the original number in most arithmetic, and it can coexist with positive numbers in a natural way.”

Practically is a useful way to represent negative numbers, since the arithmetical fundamental operations are the same, regardless whether the input or the output  is considered to be unsigned or signed.

For further information on it:’s_complement

 But what about our 4 bytes int? To understand what happens let’s look to an example:
How is number -4 represented in Java using int primitive type?
First we have to write down in binary form positive 4 using 32 bits (Java int is 32 bits) and MSB representation:
0000 0000 0000 0000 0000 0000 0000 0100

Then we have to invert all the bits to get the complement:

1111 1111 1111 1111 1111 1111 1111 1011

At this point we have to sum 1 to the previous result to get the 2’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

This results gives us a view on how Java represents a negative number internally, making bits manipulation understandable. Now enjoy yourself writing down 2’s complement for more numbers!!!



Leave a Reply

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.