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

后端 未结 5 1991

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

    The alternatives to two's complement would be

    • one's complement, which has issues due to its "negative zero"
    • sign/magnitude, which also has a negative zero
    • not assign a meaning to 10000000, in which case many functions that accept signed 8-bit integers will have to check for that invalid value, wasting time. (Unless your code is running on hypothetical hardware that treats this bit pattern as an integer NaN.)

    It's easier to just assign a meaning to that bit pattern, and the natural meaning in the two's complement representation is -128.

    For example, in two's complement, checking whether is negative mounts to checking whether its highest bit is set. In a variant where 10000000 is invalid, it's (pseudocode)

    if (highest_bit_zero(x))
        return false;
    else if (x == 0b10000000)
        ERROR
    else
        return true;
    

    You decide how to handle the error :)

提交回复
热议问题