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!
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 ?)
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With