c# uint 到 ushort 溢出,就像在本机 C 中一样

c# uint to ushort overflow like in native C

我有以下示例代码:

UInt16 a = 0x3A;
UInt16 b = 0xFFDF;
UInt16 result = Convert.ToUInt16(a - b);

第 3 行出现溢出异常的错误。但是我想获得相同的结果,就像我在 C 中减去 2 个无符号短裤,它们 over/underflow.

实现此目的最合适的方法是什么?

您可以按如下方式屏蔽低 16 位:

UInt16 result = Convert.ToUInt16((a - b) & 0xffff);