如何将有符号整数转换为无符号整数?

cod*_*lan 4 c# int

这段代码如下: -

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)

当铸造intuint要小心,因为-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)


Sac*_*ith 7

转换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)

  • 这个答案没有解释发生了什么以及有什么区别。 (5认同)