Error: Constant value '2147483648' cannot be converted to a 'int' (use 'unchecked' syntax to override)
Reason:
计算机在内部用的是补码, 所以:
byte类型的范围:(负数最小值,1既是符号位又是值位)
Dec: -128 -1 0 127
Bin: 1000 0000 1111 1111 0000 0000 0111 1111
32位Int类型范围:
Dec: -2147483648 -1 0 2147483647
Hex: 0x80000000 0xFFFFFFFF 0x00000000 0x7FFFFFFF
我们在程序中用 (int)0x80000000, 编译器看来它需要做的是 把 2147483648 转化为 Int
OVERFLOW!
-----------------------------------------------
偶然发现我以前也注意到了这个问题了:
唉,总是容易忘记
// firstly,I use INFINITE=0xFFFFFFFF, error: Cannot implicitly convert type 'uint' to 'int'
// then, I use INFINITE=(int)0xFFFFFFFF, error: Constant value '4294967295' cannot be converted to a 'int' (use 'unchecked' syntax to override)
// because, 0xFFFFFFFF changed to Int, will overflow, so it must in unchecked()
// so, this is correct: INFINITE = unchecked((int)0xffffffff)
// And then, 0xffffffff equivals to -1 in decimal when we are representing a 4 byte signed integer value.
// So, the smartest solutions is: INFINITE = -1;
public const Int32 INFINITE = -1;