# "int" variable value calculation?

Anupama Dande

Greenhorn

Posts: 10

Michael Morris

Ranch Hand

Posts: 3451

posted 13 years ago

The maximum decimal value that can be represented by an int is 2^31 - 1 or 2147483647 which in binary is 01111111111111111111111111111111. Note that every bit is on except for the first bit which is the sign bit. Now let's add 3 to it which is 00000000000000000000000000000011.

Now note that the first bit is set which indicates that we now have a negative int. Negative integral types (byte, short, int and long) are stored in 2's complement form which means that you just turn all 0s to 1s and all 1s to 0s and add 1. So, to figure the negative value we subtact 1 and complement.

That value in decimal is 2147483646 and since the sign bit is set it becomes -2147483646.

[ July 08, 2003: Message edited by: Michael Morris ]

Now note that the first bit is set which indicates that we now have a negative int. Negative integral types (byte, short, int and long) are stored in 2's complement form which means that you just turn all 0s to 1s and all 1s to 0s and add 1. So, to figure the negative value we subtact 1 and complement.

That value in decimal is 2147483646 and since the sign bit is set it becomes -2147483646.

[ July 08, 2003: Message edited by: Michael Morris ]

*Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction.* - Ernst F. Schumacher

posted 13 years ago

Remember that all integers in Java are dealt with in binary (two's complement). So, your first number (2147483647) in binary format looks like this:

01111111 11111111 11111111 11111111

When you add one to that, using binary addition, you get the following 32-bit number:

10000000 00000000 00000000 00000000

Java looks at this as a "two's complement" binary number with that leftmost "1" representing the sign; "0" is positive, "1" is negative. Without getting into too much detail on conversion, the decimal value of that number is -2147483648. When you add two to this, you get the following 32-bit number:

10000000 00000000 00000000 00000010

... which, is -2147483646 in decimal.

(Ack! I'm too slow!)

[ July 08, 2003: Message edited by: Steve Morrow ]

01111111 11111111 11111111 11111111

When you add one to that, using binary addition, you get the following 32-bit number:

10000000 00000000 00000000 00000000

Java looks at this as a "two's complement" binary number with that leftmost "1" representing the sign; "0" is positive, "1" is negative. Without getting into too much detail on conversion, the decimal value of that number is -2147483648. When you add two to this, you get the following 32-bit number:

10000000 00000000 00000000 00000010

... which, is -2147483646 in decimal.

(Ack! I'm too slow!)

[ July 08, 2003: Message edited by: Steve Morrow ]