Convert an unsigned 16 bit int to a signed 16 bit int in C#
Asked Answered
I

3

8

I'm writing a datalog parser for a robot controller, and what's coming in from the data log is a number in the range of 0 - 65535 (which is a 16 bit unsigned integer if I'm not mistaken). I'm trying to convert that to a signed 16 bit integer to display to the user (since that was the actual datatype before the logger changed it).

Can someone give me a hand?

Example:

What the values should be (0, -1, -2, -3, -4)

What the values are (0, 65535, 65534, 65533, 65532)

Impulsive answered 31/1, 2010 at 4:48 Comment(0)
C
14

Have you tried explicit casting?

UInt16 x = 65535;
var y = (Int16)x; // y = -1
Cobby answered 31/1, 2010 at 4:52 Comment(1)
Is going to crash if [X] Check for Arithmetic Overflow is on.Roundsman
R
2

Using unchecked here avoids a crash if [X] Check for Arithmetic Overflow is on:

UInt16 x = 65535;
Int16 y = unchecked((Int16)x);
Roundsman answered 3/5, 2021 at 13:48 Comment(0)
G
-2

Or like this

Or like this

Just check if UI16>32767 if yes, I16=UI16-65536, otherwise = UI16

Guilt answered 3/5, 2021 at 9:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.