Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range of signed char

Tags:

c

Why the range of signed character is -128 to 127 but not -127 to 128 ?

like image 295
Parikshita Avatar asked Oct 10 '10 01:10

Parikshita


People also ask

What is the size of signed char?

Char Size. The size of both unsigned and signed char is 1 byte always, irrespective of what compiler we use.

Why the range of char is to 127?

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.

What is the range of unsigned char variable?

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.


2 Answers

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.

like image 181
Chris Jester-Young Avatar answered Oct 04 '22 02:10

Chris Jester-Young


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).

like image 42
AnT Avatar answered Oct 04 '22 00:10

AnT