I have a temperature sensor returning 2 bytes. The temperature is defined as follows :
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; } 
double[]with the values from2^-8through2^6once, then do(dataInt16 & 0x01) * bitTemps[i]instead of re-calculating the power every timetemp = 64and then divide by two for each step.