posted 14 years ago
I am going to exapain it with 4-bit-signed integer for you to understand:
These are posible values for a 4-bit-signed integer in the positive side with the 4th bit reserved for the sign
(sign)
----4-----3----2----1----decimal
----0-----0----0----0 = 0
----0-----0----0----1 = 1
----0-----0----1----0 = 2
----0-----0----1----1 = 3
----0-----1----0----0 = 4
----0-----1----0----1 = 5
----0-----1----1----0 = 6
----0-----1----1----1 = 7
Notice how the 4th bit is never used, because it represents the sign, in this case 0 means positive. Notice also that because we cannot use the last bit, this 4-bit integer cannot reach the number 8. So this number limits are, in the positive side, 2^3-1.
Let's see the negative side:
Now, remeber that to convert a binary number to negative, you simple invert the bits and add 1, that's to say ~x+1 is the negative value of x. In other words: x == | ~x+1 | is true.
For instance, let's convert 5 (0101) to a negative number. I will not take into account the sign. Let's say x=5
~101 //invert bits (~x)
-----
=010 //partial result
+001 //add 1 (~x+1)
-----
=011 //partial result
The negative number is 1011 with the first bit turned on, because this is a negative number.
Hence, the negative numbers are:
(sign)
----4-----3----2----1----decimal
----1-----0----0----0 = -8
----1-----0----0----1 = -7
----1-----0----1----0 = -6
----1-----0----1----1 = -5
----1-----1----0----0 = -4
----1-----1----0----1 = -3
----1-----1----1----0 = -2
----1-----1----1----1 = -1
Notice how in this case, the negative numbers take adventage of their additional bit, and that is why negative numbers are always one number greater thant the positive ones. The limits of the negative numbers are, in this case: 2^3. In the positive side we could not express the number 8, because we were a bit short.
Play a bit with the Integer.toBinaryString() and you will see. Of course, in that case you would be playing with 32-bin-signed integers.
Regards,
Edwin Dalorzo
[ January 19, 2006: Message edited by: Edwin Dalorzo ]