C# – How to convert 0-65535 to Int16 equivalent -32768-32767?

c

I'm sure this is a really simple answer but I can't figure it out.
I've been presented with a value in UInt32 format, although it's maximum will be 65535.
It is reqiured to convert this to Int16 format for presentation purposes so the displayed range is -32768 to 32767.

A simple Convert.ToInt16(65535) throws an exception that 65535 is either too large or too small for Int16.

Is there an inbuilt function to handle this or can someone point me to a solution for this?

EDIT: Editted again post further discussion – 65535 is not range shifted it is in fact -32768, so I'm wanting do the conversion from a UInt32 65535 to an Int16 -32768.
Thanks for all your answers so far.

Best Answer

It depends on what you exactly want. You can use:

int i = 65535;
Int16 x = (Int16) i;

This maps 65535 to -1, 65534 to -2, etc

But if you want to shift your range 0-65535 to -32768 - +32767 then you can use

int yourvalue = 65535; // value between 0...65535
int i = yourvalue - 32768;
Int16 x = (Int16 ) i;