In 2's complement, 0-127 is represented as 00000000 to 01111111. In case of negative numbers, we invert all bits in the unsigned representation and add 1 to get the 2's complement.
(Reference: http://en.wikipedia.org/wiki/Signed_number_representations#Two.27s_complement)
so -1 in 2's complement will be:
unsigned 1 = 00000001 invert all bits = 11111110 add 1 = 11111111
But for -128, if we follow the same steps:
unsigned 128 = 10000000 invert all bits= 01111111 add 1= 10000000
so -128 and 128 have the same representation in 2's complement notation? Why isn't the range of 2's complement for 8 bits given as -127 to 128? In short, why is -128 preferred over representing unsigned 128 using the same number of bits?
-128 is preferred over 128, because of sign bit convention. In signed number representation the most significant bit is considered as sign bit. If this bit is 1, the number is negative. In the representation of 128 and -128 (10000000) this bit is 1, so it means -128, not 128.
See http://en.wikipedia.org/wiki/Sign_bit
There is no "128" in a signed byte. The range is
Total 256 values, ie 2^8.
Addendum based on comment (and rereading the question)
0x80
could have been considered as -128, or +128. Wikipedia explanation is worth reading
The two's complement of the minimum number in the range will not have the desired effect of negating the number.
For example, the two's complement of −128 in an 8-bit system results in the same binary number. This is because a positive value of 128 cannot be represented with an 8-bit signed binary numeral. Note that this is detected as an overflow condition since there was a carry into but not out of the most-significant bit. This can lead to unexpected bugs in that an unchecked implementation of absolute value could return a negative number in the case of the minimum negative. The abs family of integer functions in C typically has this behaviour. This is also true for Java. In this case it is for the developer to decide if there will be a check for the minimum negative value before the call of the function.
The most negative number in two's complement is sometimes called "the weird number," because it is the only exception. Although the number is an exception, it is a valid number in regular two's complement systems. All arithmetic operations work with it both as an operand and (unless there was an overflow) a result.
Furthermore, right-shifting a signed integer would have the CPU propagate the MSb (bit 7) to the right, which would be against simple logic if 0x80
is +128, as, after only one shift, we would obtain 0xC0
which is a negative number (-64)... (while a right-shift from a positive number can, normally, never produce a negative result).
In order to keep the MSB as the sign bit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With