关于.net:当赋值大于C#中的int max值时,如何确定整数值?

How is the integer value determined when the assigned value is larger than the int max value in C#?

本问题已经有最佳答案,请猛点这里访问。

我们有一个实例,其中分配给整数的值大于int最大值(2,147,483,647)。 它不会引发错误,它只是为整数分配了一个较小的数字。 该数字如何计算?

通过将int更改为long可以解决此问题,但是我对较小的值是如何计算并分配给int感兴趣。


int包含一个32位数字,这意味着它具有32个二进制数0或1(第一位数字表示加号表示0,减号表示1),例如:

1
2
1 in decimal  == 0000 0000 0000 0000 0000 0000 0000 0001 as int32 binary
2 147 483 647 == 0111 1111 1111 1111 1111 1111 1111 1111

因此,如果增加int.MaxValue,将得到下一个结果:

1
2 147 483 648 == 1000 0000 0000 0000 0000 0000 0000 0000

以二进制补码表示,此二进制数等于int.MinValue-2 147 483 648


1
int.MaxValue:    2,147,483,647

循环中的逻辑跟踪找到的最小数字。 您可以使用int.MaxValue来开始真正高的值,然后任何较低的数字将是有效的。

样例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;

class Program
{
static void Main()
{
int[] integerArray = new int[]
{
    10000,
    600,
    1,
    5,
    7,
    3,
    1492
};

// This will track the lowest number found
int lowestFound = int.MaxValue;

foreach (int i in integerArray)
{
    // By using int.MaxValue as the initial value,
    // this check will usually succeed.
    if (lowestFound > i)
    {
    lowestFound = i;
    Console.WriteLine(lowestFound);
    }
}
}
}

输出量

1
2
3
10000
600
1