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

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

    Why do we have the "minus 1"?

    Just answer the question: What is the maximum value of an 1-bit integer?

    One bit integer can store only two (21) values: 0 and 1. Last value is 12 = 110

    Two bit integer can store only four (22) values: 00, 01, 10 and 11. Last value is 112 = 310

    Thus, when integer can stores N, values last value will be N-1 because counting starts from zero.

    n bit integer can store 2n values. Where last will be 2n-1

    Example: One byte can store 28 (256) values. Where first is 0 and last is 255

    Why isn't the maximum just 2n?

    Because counting starts from zero. Look at first value for any n bit integer.
    For example byte: 00000000

    This would be very confusing if:
    00000001 means 2
    00000000 means 1

    would not? ;-)

提交回复
热议问题