Why is the range of signed byte is from -128 to 127 (2's complement) and not from -127 to 127?

后端 未结 5 1996

I read Why is the range of bytes -128 to 127 in Java? it says

128 is 10000000. Inverted, it\'s 01111111, and adding one gets 10000000 again

5条回答
  •  隐瞒了意图╮
    2020-12-07 19:38

    Why is the range of unsigned byte is from -128 to 127?

    It's not. An unsigned byte (assuming 8-bit) is from 0 to 255.

    The range of a signed byte using 2's complement is from -128 to 127, directly from the definition of 2's complement:

    01111111 = +127
    01111110 = +126
    01111101 = +125
    ...
    00000001 = +1
    00000000 =  0
    11111111 = -1
    ...
    10000010 = -126
    10000001 = -127
    10000000 = -128
    

    so is representation of -128 10000000 or 110000000 ?

    In 8-bit, it's 10000000, in a hypothetical 9-bit representation it's 110000000.

    Why not simply make the lower range -127 for 8 bits?

    Artificially restricting the range to -127 wouldn't achieve very much; you'd be disallowing a perfectly valid value, and generally making code more complex (what else would you do with the bit pattern 10000000?).

提交回复
热议问题