eKKiM
eKKiM

Reputation: 431

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?

Upvotes: 8

Views: 1952

Answers (1)

Dmitry
Dmitry

Reputation: 14059

You could mask lower 16 bits as follows:

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

Upvotes: 9

Related Questions