8

I have the following piece of example code:

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

line 3 errors with an Overflow exception. However i want to achieve the same result like i would subtract 2 unsigned shorts in C and they over/underflow.

What is the most proper way to achieve this?

eKKiM
  • 421
  • 5
  • 18

1 Answers1

9

You could mask lower 16 bits as follows:

UInt16 result = Convert.ToUInt16((a - b) & 0xffff);
Dmitry
  • 13,797
  • 6
  • 32
  • 48
  • You can also use the [unchecked context](https://msdn.microsoft.com/library/a569z7k8.aspx): `ushort result = unchecked((ushort)(a-b));` – Javier Martín Jan 11 '16 at 22:26