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

后端 未结 5 2006

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:40

    so is representation of -128 10000000 or 110000000 ? Is the representaion bit dependent ?

    In a 9-bit world, it would be 110000000. In a 16-bit world, it would be 1111111110000000. At least, as long as we're talking two's complement.

    Why not simply make the lower range -127 for 8 bits instead of writing -128 as 10000000 ?

    As larsmans pointed out, you'd end up with an "invalid" value, which you would constantly have to check against. Two's complement has been chosen because it's so easy for the ALU to handle. Just like byte widths have been chosen to be power-of-two (which was not always the case either). At a hardware level, two's complement addition is identical to unsigned, so no special instructions or extra hardware is needed (unlike with one's complement).

    With things the way they are, all values with the highest bit set are negative, all values with the highest bit unset are non-negative (positive or zero). Easy, isn't it? The negative range being one larger than the positive range is simply an artifact of trying to keep two's complement simple.

提交回复
热议问题