Why the range of signed character is -128
to 127
but not -127
to 128
?
Char Size. The size of both unsigned and signed char is 1 byte always, irrespective of what compiler we use.
An 8 bit signed integer using one's complement representation can only have values from -127 to -0 and from +0 to +127. That's because there are two ways to represent zero; a positive zero and a negative zero. Same with signed magnitude representation.
unsigned char is a character datatype where the variable consumes all the 8 bits of the memory and there is no sign bit (which is there in signed char). So it means that the range of unsigned char data type ranges from 0 to 255.
That is because of the way two's complement encoding works: 0 is treated as a "positive" number (signed bit off), so, therefore, the number of available positive values is reduced by one.
In ones' complement encoding (which is not very common nowadays, but in the olden days, it was), there were separate values for +0 and -0, and so the range for an 8-bit quantity is -127 to +127.
In 8-bit 2's complement encoding numbers -128
and +128
have the same representation: 10000000
. So, the designer of the hardware is presented with an obvious dilemma: how to interpret bit-pattern 10000000
. Formally, it will work either way. If they decide to interpret it as +128
, the resultant range will be -127..+128
. If they decide to interpret it as -128
, the resultant range will be -128..+127
.
In actual real-life 2's complement representation the latter approach is chosen because it satisfies the following nice convention: all bit-patterns with 1
in higher-order bit represent negative numbers.
It is worth noting though, that language specification does not require 2's-complement implementations to treat the 100...0
bit pattern as a valid value in any signed integer type. E.g. implementations are allowed to restrict 8-bit signed char
to -127..+127
range and regard 10000000
as an invalid bit combination (trap representation).
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