【问题标题】:How can I convert a signed integer into an unsigned integer?如何将有符号整数转换为无符号整数?
【发布时间】:2017-07-21 18:10:21
【问题描述】:

这段代码是这样的:-

int x = -24;  
uint y = (uint) x;  
Console.WriteLine("*****" + y + "********");  
// o/p is *****4294967272********  

为什么在 C# 中出现这种行为,详细阐述会有所帮助。谢谢大家。

【问题讨论】:

  • 当你已经有代码时,你为什么要问如何将int 转换为uint?你在问什么?
  • 您是否尝试过使用 Convert.ToUInt32() 内置函数?

标签: c# integer uint


【解决方案1】:

有几种方法可以将int 转换为uint

int x;

技巧#1

uint y = Convert.ToUInt32(x);

技巧#2

uint y = checked((uint) x);

技巧#3

uint y = unchecked((uint) x);

技巧#4

uint y = (uint) x;

【讨论】:

  • 这个答案没有解释发生了什么以及有什么区别。
【解决方案2】:

负数(如-24)表示为二进制补码,参见

en.wikipedia.org/wiki/Two's_complement

了解详情。你的情况

   24     = 00000000000000000000000000011000
  ~24     = 11111111111111111111111111100111
  ~24 + 1 = 11111111111111111111111111101000 =
          = 4294967272

将int 转换为uint 时要小心,因为-24 超出 uint 范围(即[0..uint.MaxValue])你可以抛出OverflowException。更安全的实现是

 int x = -24;  
 uint y = unchecked((uint) x); // do not throw OverflowException exception  

【讨论】:

  • 正确。按预期工作。
  • OP 的代码在没有 unchecked 关键字的情况下工作。
  • 4294967295 是可以采用的最大 uint 值,并且由于 4294967272 低于该数字,因此它不能给出 OverflowException,因此不需要 unchecked。实际上从 int 转换为 uint 永远不会得到 OverflowException...
  • @sotn:请进行一个简单的实验:int x = -24; uint y = checked((uint) x); 并查看OverflowException。它的-24 超出了uint.MinValue(即0)
【解决方案3】:

试试下面的代码

int x = -24;  
Console.WriteLine("*****" + Convert.ToUInt32(x) + "********");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    相关资源
    最近更新 更多