Question

As we know that the range of char is -128 to 127.

The 2's compliment of -128 and the binary of 128 is same, which is

10000000

So why the range of char is -128 to 127 but not -127 to 128 .
Where as in case of int , 128 and -128 both are different.

Was it helpful?

Solution

In twos-complement notation, whenever the high-order bit is 1, the number is negative. So the biggest positive number is

01111111 = 127

and the smallest negative number is

10000000 = -128

The same thing happens for int, but its range is much larger. The biggest positive int is

01111111 11111111 11111111 11111111 = 2147483647

and the smallest negative int is

10000000 00000000 00000000 00000000 = -2147483648

As you can see, in both cases, the smallest negative is 1 more than the biggest positive.

You might be wondering, If there are the same number of bits other than the sign bit, why are there more negative numbers than positives? That's because you're not counting 0. It has 0 in the high-order bit, so it's considered positive in this notation. When you include that, there are 128 negative chars, and 128 non-negative chars, and they balance equally.

OTHER TIPS

A character has 8 bits. So the bit pattern for -128 and 128 are the same when you have 8 bits to deal with. (ignoring the sign bit)

Now the int. It has more bits so the MSB is not -128 but a larger -ve number depending on the platform.

It does exhibit the same problem at a "higher" number

Look 128 is

10000000

But by default char is signed compiler treats first bit as sign bit and treats the no. as negative and calculates its 2s complement ( because MSB is 1)

2s complement is
 01111111
      +        1
 10000000

So - 128 is stored To store +128 compiler have to consider 9 bits that is to interpret

010000000

Here MSB is 0 for positive no. But size is of 9 bits this shows why char only accomodate upto +127 and if we want to store +128 then -128 will be stored as explained above

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top