本文介绍了如何将有符号整数转换为无符号整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这段代码就像:-
int x = -24;
uint y = (uint) x;
Console.WriteLine("*****" + y + "********");
// o/p is *****4294967272********
为什么在C#中这种类型的行为,详细的阐述会有所帮助.谢谢大家.
Why this type of behavior in C#, Detailed elaboration would be helpful. Thankyou all.
推荐答案
负数(如-24
)表示为二进制补码,请参见
Negative numbers (like -24
) are represented as a binary complement, see
en.wikipedia.org/wiki/Two's_complement
有关详细信息.就您而言
for details. In your case
24 = 00000000000000000000000000011000
~24 = 11111111111111111111111111100111
~24 + 1 = 11111111111111111111111111101000 =
= 4294967272
将int
强制转换为uint
时要小心,因为-24
超出了 uint
范围([0..uint.MaxValue]
),因此可能会抛出OverflowException
.更安全的实现是
When casting int
to uint
be careful, since -24
is beyond uint
range (which [0..uint.MaxValue]
) you can have OverflowException
being thrown. A safier implementation is
int x = -24;
uint y = unchecked((uint) x); // do not throw OverflowException exception
这篇关于如何将有符号整数转换为无符号整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!