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?
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 numberThen 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)