views:

374

answers:

8

Whats the mathematical formulae to calculate the MIN and MAX value of an integral type using your calculator. I know you can use Integer.Max or Integer.Min etc or look it up on msdn however I want to know how to calculate it.

+11  A: 

For unsigned types:

  • Min value = 0
  • Max value = (2 ** (number of bits)) - 1

So, for UInt32:

Min value = 0

Max value = (2 ** 32) - 1
          = 4294967296 - 1
          = 4294967295

For signed types:

  • Min value = 0 - (2 ** (number of bits - 1))
  • Max value = (2 ** (number of bits - 1)) - 1

So, for Int32:

Min value = 0 - (2 ** (32 - 1))
          = 0 - (2 ** 31)
          = 0 - 2147483648
          = -2147483648

Max value = (2 ** (32 - 1)) - 1
          = (2 ** 31) - 1
          = 2147483648 - 1
          = 2147483647
LukeH
+1 Way better than mine!
Preet Sangha
Thanks for the effort put into answering my very simple question!
Jonathan
Simplicity can be complicated.
Filip Ekberg
+3  A: 

I'm using a 32bits signed integer in this example. 31 bits are used for the value creating 2^31 possibilities. As zero has to be included, you have to subtract one.

2^31-1

When negative, zero doesn't have to be included, thus you get the full range.

-2^31

In case of a unsigned integer, the max is simply 2^32-1, and the min 0.

Dykam
+1 for explanation instead of just a formula.
Konrad Rudolph
+1  A: 

You need to know how many bits the type is and whether it is signed or not.

For example, an int is 32-bits in C# and is signed. This means there are 31 bits to represent the number (1 bit is used to determine negative or postive). So you would calculate 231 and subtract one which is 2147483647, (which is what Integer.MaxValue returns).

Similary a byte is 8 bits and not signed so the max value is 28 -1 or 255.

Paolo
Whoops! Corrected
Paolo
A: 

The Min/Max value of an Integer variable is derived from the amount of bits used (usually to the power of 2, ie 2bits, 4bits, 8bits). An INT in C# uses 32 bits, and as such can have a MAX value of 4,294,967,295 - as this is the maximum value 32 bits of data can represent - as is my understanding, anyway.

Seidr
A: 

If your calculator has a decimal-to-binary conversion (dec-to-hex would also work), try converting Int32.MaxValue and see if you spot the pattern ...

Hans Kesting
A: 

I believe you'll find this helpful:
Integer (Computer Science) @ Wikipedia

Rubys
A: 

An example for your question answer

int signed:

Min=(1 << ((sizeof(int) * 8) - 1));
Max=~(1 << ((sizeof(int) * 8) - 1));

also

Min=~(int)((~((uint)0))>>1);
Max=(int)((~((uint)0))>>1);

int unsigned:

Min=0;
Max=~((uint)0);
Betamoo