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;

相关文章:

  • 2021-09-25
  • 2022-12-23
  • 2021-10-21
  • 2021-10-26
  • 2021-05-21
  • 2022-12-23
  • 2021-12-15
  • 2022-01-14
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-25
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案