Why is the maximum value of an unsigned n-bit integer 2^n-1 and not 2^n?

后端 未结 12 1191
萌比男神i
萌比男神i 2020-11-28 06:01

The maximum value of an n-bit integer is 2n-1. Why do we have the \"minus 1\"? Why isn\'t the maximum just 2n?

12条回答
  •  自闭症患者
    2020-11-28 06:36

    In most programming languages integer is a signed value (see two's complement).

    For example, in Java and .NET integer most left byte is reserved for sign:

    • 0 => positive or zero number
    • 1 => negative number

    Then the maximum value for 32-bit number is limited by 2^31. And adding -1 we get 2^31 - 1.

    Why does -1 appear?

    Look at more simple example with unsigned Byte (8-bits):

      1  1  1  1  1  1  1  1
    128 64 32 16  8  4  2  1  <-- the most right bit cannot represent 2
    --- --------------------
    128 + 127 = 255 
    

    As other guys pointed out the most right bit can have a maximum value of 1, not 2, because of 0/1 values.

    Int32.MaxValue = 2147483647 (.NET)
    

提交回复
热议问题