views:

109

answers:

4

Possible Duplicate:
2's Complement - Defined

I know int32 is has a lenght of 32 bytes. I assume it has 2^32 values but as half of them needs to be under zero, I guess it has something to do with this. I would like to know why exactly int32 has max. positive number 2^31 -1.

+2  A: 
dan04
A: 

This first 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
A: 

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
A: 

2^32 is about 4.2 billion. This is a 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^32-1 (instead of 1 to 2^32, 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 2^1, or by half. This leaves 2^31, 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