这段代码就像:-
int x = -24;
uint y = (uint) x;
Console.WriteLine("*****" + y + "********");
// o/p is *****4294967272********
为什么 C# 中会出现这种类型的行为,详细阐述会很有帮助。谢谢你们。
负数(例如-24
) 表示为二元补码, see
en.wikipedia.org/wiki/Two's_complement https://en.wikipedia.org/wiki/Two's_complement
了解详情。在你的情况下
24 = 00000000000000000000000000011000
~24 = 11111111111111111111111111100111
~24 + 1 = 11111111111111111111111111101000 =
= 4294967272
铸造时int
to uint
小心点,因为-24
is beyond uint
范围(其中[0..uint.MaxValue]
) 你可以有OverflowException
被抛出。更安全的实施是
int x = -24;
uint y = unchecked((uint) x); // do not throw OverflowException exception
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)