0

I am trying to convert a hex string to a float number in Javascript.

Suppose that I have the hex string "0082d241". Using this online converter and selecting Swap endianness, the correct float value is 26,3135.

I know that this is the correct answer because it is from a TMP36 sensor.

I have tried some other examples that I found here on SO, such as Converting hexadecimal to float in javascript, but none of them worked.

robinCTS
  • 5,746
  • 14
  • 30
  • 37
kots
  • 1
  • 1
  • 3

1 Answers1

3

The first step is to swap endianness, using the source code found on the page that you've shown.

Then you can convert the hexadecimal string to a float value.

function flipHexString(hexValue, hexDigits) {
  var h = hexValue.substr(0, 2);
  for (var i = 0; i < hexDigits; ++i) {
    h += hexValue.substr(2 + (hexDigits - 1 - i) * 2, 2);
  }
  return h;
}


function hexToFloat(hex) {
  var s = hex >> 31 ? -1 : 1;
  var e = (hex >> 23) & 0xFF;
  return s * (hex & 0x7fffff | 0x800000) * 1.0 / Math.pow(2, 23) * Math.pow(2, (e - 127))
}

console.log(hexToFloat(flipHexString("0x0082d241", 8)));
console.log(hexToFloat(flipHexString("0x5d7e2842", 8)));
Teh
  • 2,767
  • 2
  • 15
  • 16
  • sorry for the late response, but this returns always the same value: 26.3134765625 whatever the measurment is. (i changed the "0x0082d241" in the last line of your code" – kots Aug 18 '17 at 06:20
  • @kots There must be something wrong in your code. I've added a working code snippet to my answer to show you the results with two different hex strings – Teh Aug 18 '17 at 07:18
  • still have trouble. maybe because i use it with node red? here is how i use it: ms = msg.payload.data; function flipHexString(hexValue, hexDigits) { var h = hexValue.substr(0, 2); for (var i = 0; i < hexDigits; ++i) { h += hexValue.substr(2 + (hexDigits - 1 - i) * 2, 2); } return h; } function hexToFloat(hex) { var s = hex >> 31 ? -1 : 1; var e = (hex >> 23) & 0xFF; return s * (hex & 0x7fffff | 0x800000) * 1.0 / Math.pow(2, 23) * Math.pow(2, (e - 127)); } msg.payload=hexToFloat(flipHexString(ms, 8)); return msg; @Teh – kots Aug 18 '17 at 07:40
  • @kots Looks good to me, you should debug step by step what input you're getting in msg.payload.data and what is being returned, until you find what's wrong – Teh Aug 18 '17 at 07:56
  • the code now change the values but they are in wrong format. It should be 26.2251 and it is 5.45211154 e^-19 . – kots Aug 18 '17 at 07:59