Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# uint to ushort overflow like in native C

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?

like image 942
eKKiM Avatar asked Jan 11 '16 21:01

eKKiM


1 Answers

You could mask lower 16 bits as follows:

UInt16 result = Convert.ToUInt16((a - b) & 0xffff);
like image 54
Dmitry Avatar answered Oct 13 '22 02:10

Dmitry