开发者

Why has the Int32 type a maximum value of 2³¹ − 1?

I know Int32 has a length of 32 bits (4 bytes). I assume it has 2³² values but as half of them must be under zero, I guess it has something to do with this.

I would like to know why exactly Int3开发者_如何学编程2 has maximum positive number 2³¹ − 1.


This most significant bit is used to code the sign (1 meaning negative), so only 31 bits are available for the actual value.

Int32.MaxValue =  2^31 - 1 = 01111111111111111111111111111111
                  1        = 00000000000000000000000000000001
                  0        = 00000000000000000000000000000000
                 -1        = 11111111111111111111111111111111
Int32.MinValue = -2^31     = 10000000000000000000000000000000


2³² possible values

− 2³¹ values used for negative integers

− 1 value used for zero

= 2³¹ − 1 values available for positive integers


2³² is about 4.2 billion. This is the maximum number of VALUES that a binary number with 32 digits (a 32-bit number) can represent.

Those values can be any values in any range. In an UNSIGNED 32-bit number, the valid values are from 0 to 2³² − 1 (instead of 1 to 2³², but the same number of VALUES, about 4.2 billion).

In a SIGNED 32-bit number, one of the 32 bits is used to indicate whether the number is negative or not. This reduces the number of values by a factor of 2¹, or by half. This leaves 2³¹, which is about 2.1 billion. This means the range is now about −2.1 billion to 2.1 billion. Same number of values, different range.


You have 2^31 values below zero (minimum value = -2^31), 2^31-1 values above zero and zero itself. That makes 2^31 + 2^31-1 + 1 = 2*2^31 = 2^32 values :) ...

The other explanation involves the way how negative numbers are represented (using the two-complement): Shortly, the most-significant bit indicates a negative number, so you have 2^31 positive numbers (including zero) left, which gives us the range 0..2^31-1

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜