Why is there one more negative int than positive int?

后端 未结 3 1747
独厮守ぢ
独厮守ぢ 2021-01-12 07:28

The upper limit for any int data type (excluding tinyint), is always one less than the absolute value of the lower limit.

For example, the

3条回答
  •  孤城傲影
    2021-01-12 08:00

    The types you provided are signed integers. Let's see one byte(8-bit) example. With 1 byte you have 2^8 combinations which gives you 256 possible numbers to store.

    Now you want to have the same number of positive and negative numbers (each group should have 128).

    The point is 0 doesn't have +0 and -0. There is only one 0.

    So you end up with range -128..-1..0..1..127.

    The same logic works for 16/32/64-bit.

    EDIT:

    Why the range is -128 to 127?

    It depends on how you represent signed integer:

    • Signed magnitude representation
    • Ones' complement
    • Two's complement

提交回复
热议问题