1

Im trying to parse the data coming from some sensors, The data I recive is a hexadecimal number f.e.: '450934644ad7a38441' I want to extract the last 8 characters, that are the value for temperature taken, and transform it into a readable number. I tried this website: https://www.scadacore.com/tools/programming-calculators/online-hex-converter/

Here when you input d7a38441 it is processed and the wanted number is under Float - Little Endian (DCBA) system. Also the conversion it`s doing is under UINT32 - Big Endian (ABCD) system

How do I convert this number into float? I Tried reading some other questions here but couldnt find a solution. parseFloat() gives me NaN.

I would appreciate some light.

var data = '450934644ad7a38441';

function main(data) {

  var result = [
    {      
        "key": "temperature",
        "value": parseInt('0x'+data.substring(10))
    }
    ]
  
  
  return result;
}

console.log(main(data));
// expected output: Array [Object { key: "temperature", value: 16.58 }]
  • [Does this answer your question?](https://stackoverflow.com/questions/5055723/converting-hexadecimal-to-float-in-javascript) – secan Apr 12 '21 at 09:12
  • Does this answer your question? [Hex String to INT32 - Little Endian (DCBA Format) Javascript](https://stackoverflow.com/questions/43239567/hex-string-to-int32-little-endian-dcba-format-javascript) – Justinas Apr 12 '21 at 09:13
  • Thanks for the comments, I tried adapting this solutions already but im unable to make it works. Im new into javaScript so its harder for me to find a suitable answer for my problem – Luis urrechaga Apr 12 '21 at 11:36
  • @MohamedRady yeah, I tried, using parseInt(data.substring(10),16) is similar to: parseInt('0x'+data.substring(10)) – Luis urrechaga Apr 12 '21 at 11:51
  • 3
    On a side note, if you want *the last 8 characters*, `data.substr(-8)` might be semantically better. – Yoshi Apr 12 '21 at 12:01

1 Answers1

2

I think this is what you need. String received by function yourStringToFloat is your data variable received by main function in your example. Of course you can fix precision according to your needs.

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))
}

function yourStringToFloat(str){

    return hexToFloat(flipHexString("0x"+str.substr(10), 8))

}

console.log(yourStringToFloat('450934644ad7a38441'));
Karol Pawlak
  • 440
  • 4
  • 15