confusion regarding range of char

回眸只為那壹抹淺笑 提交于 2021-02-11 12:36:01

问题


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.


回答1:


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.




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/21951828/confusion-regarding-range-of-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!