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

后端 未结 12 1216
萌比男神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:41

    2^32 in binary:

    1 00000000 00000000 00000000 00000000
    

    2^32 - 1 in binary:

    11111111 11111111 11111111 11111111
    

    As you can see, 2^32 takes 33 bits, whereas 2^32 - 1 is the maximum value of a 32 bit integer.

    The reason for the seemingly "off-by-one" error here is that the lowest bit represents a one, not a two. So the first bit is actually 2^0, the second bit is 2^1, etc...

提交回复
热议问题