Range of signed char

前端 未结 6 988
盖世英雄少女心
盖世英雄少女心 2020-12-02 21:13

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

6条回答
  •  臣服心动
    2020-12-02 21:57

    I think an easy way to explain this for the common soul is :

    A bit is a value 0 or 1, or 2 possibilities

    A 2-bit holds two combinations or 0 and 1 for four possible values : 00, 01, 10, and 11.

    A 3-bit holds three combinations for a total of eight possible values : 000 to 111.

    Thus n-bits holds n combinations for a total of 2^n possible values. Therefore, an 8-bit value is 2^8 = 256 possible values.

    For signed numbers, the most significant bit (the first one reading the value from left to right) is the sign bit; that leaves a possibility of 2^(n-1) possible values. For an 8-bit signed number, this is 2^7 = 128 possible values for each sign. But since the positive sign includes the zero (0 to 127 = 128 different values, and 128 + 128 = 2^8 = 256), the negative sign includes -1 to... -128 for 128 different values also. Where :

    10000000 = -128
    ...
    11111111 = -1
    00000000 = 0
    ...
    01111111 = 127
    

提交回复
热议问题