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

5
  • Does this answer your question? Commented Apr 12, 2021 at 9:12
  • Does this answer your question? Hex String to INT32 - Little Endian (DCBA Format) Javascript Commented Apr 12, 2021 at 9: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 Commented Apr 12, 2021 at 11:36
  • @MohamedRady yeah, I tried, using parseInt(data.substring(10),16) is similar to: parseInt('0x'+data.substring(10)) Commented Apr 12, 2021 at 11:51
  • 3
    On a side note, if you want the last 8 characters, data.substr(-8) might be semantically better. Commented Apr 12, 2021 at 12:01

1 Answer 1

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'));

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

1 Comment

Thanks for the reply Karol, I really appreciate! This helped me a lot

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.