26

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 Int32 has maximum positive number 2³¹ − 1.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Petr
  • 519
  • 2
  • 7
  • 12
  • 1
    duplicate of [Why is the maximum value of an unsigned n-bit integer 2^n-1 and not 2^n?](https://stackoverflow.com/questions/5771520/why-is-the-maximum-value-of-an-unsigned-n-bit-integer-2n-1-and-not-2n) – phuclv Jun 16 '17 at 12:53
  • Related: [What is “2's Complement”?](https://stackoverflow.com/questions/1049722/2s-complement-defined) – Theodor Zoulias Oct 26 '22 at 12:03

4 Answers4

65

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
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • 1
    If we are going to consider 0 as positive number(hypothetically), then we have equal number of values besides the imaginary line between -1 and 0 . – Shruti Saagar Jun 11 '21 at 08:37
38

2³² possible values

− 2³¹ values used for negative integers

− 1 value used for zero

= 2³¹ − 1 values available for positive integers

dan04
  • 87,747
  • 23
  • 163
  • 198
31

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.

Phil Gilmore
  • 1,286
  • 8
  • 15
  • @HashimAziz: The flaw being that, without referencing two's complement representation, it doesn't explain why the maximum value is 2³¹ − 1, while the minimum is -2³¹. – ShadowRanger May 01 '22 at 18:32
1

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

MartinStettner
  • 28,719
  • 15
  • 79
  • 106