C # uint for ushort overflow like in original C

I have the following sample code snippet:

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

line 3 error with overflow exception. However, I want to achieve the same result as if I subtracted 2 unsigned shorts in C and they exceeded / underflow.

What is the best way to achieve this?

+8
c # integer-overflow
source share
1 answer

You can mask the lower 16 bits as follows:

 UInt16 result = Convert.ToUInt16((a - b) & 0xffff); 
+9
source share

All Articles