1

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.

4

8 回答 8

12

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
于 2010-05-06T09:29:37.067 回答
3

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.

于 2010-05-06T09:29:59.497 回答
1



您的问题答案int 签名示例:

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

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

整数无符号:

Min=0;
Max=~((uint)0);
于 2010-05-06T09:51:47.920 回答
1

您需要知道该类型有多少位以及它是否已签名。

例如,anint在 C# 中是 32 位的并且是有符号的。这意味着有 31 位来表示数字(1 位用于确定负数或正数)。因此,您将计算 2 31并减去 2147483647(这是 Integer.MaxValue 返回的值)。

同样 abyte是 8 位并且没有符号,所以最大值是 2 8 -1 或 255。

于 2010-05-06T09:30:43.343 回答
0

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

于 2010-05-06T09:30:58.897 回答
0

如果您的计算器有十进制到二进制的转换(十进制到十六进制也可以),请尝试转换 Int32.MaxValue 并查看您是否发现了模式...

于 2010-05-06T09:31:35.120 回答
0

我相信你会发现这很有帮助:
整数(计算机科学)@维基百科

于 2010-05-06T09:31:54.717 回答
0

Integer 变量的 Min/Max 值源自使用的位数(通常为 2 的幂,即 2bits、4bits、8bits)。C# 中的 INT 使用 32 位,因此可以具有 4,294,967,295 的 MAX 值 - 因为这是 32 位数据可以表示的最大值 - 无论如何,这是我的理解。

于 2010-05-06T09:30:43.920 回答