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:
Upper limit =
Lower limit =
General formula for non negative upper limit where n is the number of bits.
General formula for negative lower limit where n is the number of bits.
If the primitive is unsigned the lower limit is 0, while the upper limit becomes
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.
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.