这段代码如下: -
int x = -24;
uint y = (uint) x;
Console.WriteLine("*****" + y + "********");
// o/p is *****4294967272********
Run Code Online (Sandbox Code Playgroud)
为什么在C#中这种行为,详细阐述会有所帮助.谢谢你们.
Dmi*_*nko 17
负数(如-24)表示为二进制补码,请参阅
en.wikipedia.org/wiki/Two's_complement
详情.在你的情况下
24 = 00000000000000000000000000011000
~24 = 11111111111111111111111111100111
~24 + 1 = 11111111111111111111111111101000 =
= 4294967272
Run Code Online (Sandbox Code Playgroud)
当铸造int到uint要小心,因为-24是超出 uint范围(这[0..uint.MaxValue])可以已经OverflowException被抛出.安全实施是
int x = -24;
uint y = unchecked((uint) x); // do not throw OverflowException exception
Run Code Online (Sandbox Code Playgroud)
转换int为的方法很少uint
int x;
Run Code Online (Sandbox Code Playgroud)
技术#1
uint y = Convert.ToUInt32(x);
Run Code Online (Sandbox Code Playgroud)
技术#2
uint y = checked((uint) x);
Run Code Online (Sandbox Code Playgroud)
技术#3
uint y = unchecked((uint) x);
Run Code Online (Sandbox Code Playgroud)
技术#4
uint y = (uint) x;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9414 次 |
| 最近记录: |