开发者

Min and Max value of integral type in C#

Whats the mathematical formulae to calculate the MIN and MAX value of an integral type usin开发者_高级运维g 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.


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


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.


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.


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 ...


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);


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.


http://en.wikipedia.org/wiki/Integer_%28computer_science%29


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜