0

I have a temperature sensor returning 2 bytes. The temperature is defined as follows :

bit to temperature conversion table

What is the best way in C# to convert these 2 byte to a float ?

My sollution is the following, but I don't like the power of 2 and the for loop :

static void Main(string[] args) { byte[] sensorData = new byte[] { 0b11000010, 0b10000001 }; //(-1) * (2^(6) + 2^(1) + 2^(-1) + 2^(-8)) = -66.50390625 Console.WriteLine(ByteArrayToTemp(sensorData)); } static double ByteArrayToTemp(byte[] data) { // Convert byte array to short to be able to shift it if (BitConverter.IsLittleEndian) Array.Reverse(data); Int16 dataInt16 = BitConverter.ToInt16(data, 0); double temp = 0; for (int i = 0; i < 15; i++) { //We take the LSB of the data and multiply it by the corresponding second power (from -8 to 6) //Then we shift the data for the next loop temp += (dataInt16 & 0x01) * Math.Pow(2, -8 + i); dataInt16 >>= 1; } if ((dataInt16 & 0x01) == 1) temp *= -1; //Sign bit return temp; } 
2
  • 1
    Populate a const or static double[] with the values from 2^-8 through 2^6 once, then do (dataInt16 & 0x01) * bitTemps[i] instead of re-calculating the power every time Commented Sep 24, 2021 at 10:56
  • 1
    You could also go from MSB to LSB, starting with temp = 64 and then divide by two for each step. Commented Sep 24, 2021 at 10:58

1 Answer 1

2

This might be slightly more efficient, but I can't see it making much difference:

static double ByteArrayToTemp(byte[] data) { if (BitConverter.IsLittleEndian) Array.Reverse(data); ushort bits = BitConverter.ToUInt16(data, 0); double scale = 1 << 6; double result = 0; for (int i = 0, bit = 1 << 14; i < 15; ++i, bit >>= 1, scale /= 2) { if ((bits & bit) != 0) result += scale; } if ((bits & 0x8000) != 0) result = -result; return result; } 

You're not going to be able to avoid a loop when calculating this.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.