I've got a 2 byte array (21, 121) that needs to be converted to a decimal value. The piece of hardware I read the numbers from includes this handy little table in the manual:
The problem is that I'm not sure what this handy little table is trying to tell me. Can someone help interpret it and suggest a way I can convert it to decimal using c#?
I've generally used BitConverter
to get this converted, but in this case, I get a value of 30977. Since this is a temperature value, I find it hard to believe it's that hot... so I suspect my regular use of BitConvert isn't sufficient.
This table tells you that you can get the value this way:
public static float GetTemperature(byte[] data, int start = 0)
{
return (sbyte)data[start] + data[start + 1] / 256.0f;
}
EDIT: negative numbers were not decoded correctly.
EDIT: as others mentioned, the table shows you that how the value is encoded. The top row is the bit index in the binary data, the bottom row is the weight of the bit. All you have to do is to multiply all the bit values with their weights, and add them together. Sidenote: the first bit is not a sign, it shows that it is encoded in two's complement. Fortunately, you don't have to calculate the separate bits, because this is pretty much how the computer stores all the data. It is like a signed short value stored on two bytes, scaled by 256 (2**8).
BitConverter uses platform-dependent byte order, so basically you can't use it here.
Another way to get this right:
public static short GetShort(byte[] data, int start)
{
return (short)(data[start] * 256 + data[start + 1]);
}
public static float GetTemperature(byte[] data, int start)
{
return GetShort(data, start) / 256.0f;
}
This table tells you that the low byte value describes values between 0,0039 (the first bit in the byte) and 0,5 (the last bit in the byte). Combined it is close to 1, the first bit in the high byte. The highest value is 128, which is the sixth bit of the high byte. The seventh bit tells you if the number is negative or positive.
So this is a signed integer of 8 bits with some extra precision.
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