Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect negative Hex Values in C#?

Tags:

c#

hex

I am working on a driver for a temperature sensor. The values are coming in Hex form and they are stored like:

string tempHex = "08C5"; //-> Would be 22,45°C

The problem is, the sensor can also notice negative values and I have no idea how I can detect the 2's complement in C#.

Maybe you can help me. Thank you!

like image 266
xileb0 Avatar asked May 15 '15 06:05

xileb0


People also ask

How do you know if a hex is negative?

If a hex value written with all its bits having something > 7 as its first hex digit, it is negative. All 'F' at the beginning or the first digit means is that the value is negative, it is not calculated. For exemple if the hex value is written in 32 bits: FFFFF63C => negative ( -2500 ?)

Is hex signed or unsigned?

A hexadecimal value is int as long as the value fits into int and for larger values it is unsigned , then long , then unsigned long etc. See Section 6.4.

What is hexadecimal code?

Hexadecimal is a numbering system with base 16. It can be used to represent large numbers with fewer digits. In this system there are 16 symbols or possible digit values from 0 to 9, followed by six alphabetic characters -- A, B, C, D, E and F.


1 Answers

static public double Temp(string hex)
{
    return Convert.ToInt16(hex,16)*0.01;
}

Values from 0000 to 7FFF will be positive, 8000 to FFFF will be negative. Luckily, Convert.ToInt16() does this all for you, as this is exactly how the numbers are stored internally on all modern computers. You just have to multiple by 0.01 to get Celsius.

like image 103
Mark Lakata Avatar answered Sep 18 '22 12:09

Mark Lakata