Search code examples
javascripthexendianness

convert hex to float32_LE


I hope you and your family are well. I am getting difficulty in convert hex to float32_LE. I tried some different online JavaScript editors but not working well. If someone has an idea how can find the best resources to convert hex to float32_LE. I appreciate then in advance. I have hex value = 0xcf91873b. It should be 0.004137255. I have found direct conversation but I need some background stuff. so I can use it in code.

Thank you kind regards.


Solution

  • The DataView.prototype.getFloat32() method allows you to take an unsigned integer and return the floating-point representation. The first parameter is the byteOffset; this should be 0. The method also takes a littleEndian parameter; we want to set this to true.

    The final unpacked float 32 value is 0.004137254785746336

    Edit: I added the ability to decode multiple hex values.

    // https://stackoverflow.com/a/49221327/1762224
    const parseFloat = (hex, littleEndian) => {
      const
        octets = Math.floor(hex.replace(/^0x/, '').length / 2),
        dataView = new DataView(new ArrayBuffer(octets));
      dataView.setUint32(0, parseInt(hex, 16));
      return dataView.getFloat32(0, littleEndian);
    }
    
    const ui = {
      input: document.querySelector('#input'),
      output: document.querySelector('#output'),
      convert: document.querySelector('#convert')
    };
    
    const handleConvert = (e) => {
      ui.output.value = ui.input.value.trim().split(/\s+/).map(hex =>
        parseFloat(hex, true)).join(' ');
    };
    
    ui.convert.addEventListener('click', handleConvert);
    body,html{width:100%;height:100%;margin:0;padding:0;background:#000;color:#0f0}
    body{display:flex;flex-direction:column;justify-content:center;align-items:center}
    textarea{flex:1;margin:.5em;width:calc(100% - 2em);font-family:monospace;border:thin solid #0f0;background:#000;color:#0f0;resize:none}
    button{margin:0;background:#000;color:#0f0;border:thin solid #0f0;padding:.5em}
    button:hover{background:#0f0;color:#000;cursor:pointer}
    <textarea id="input">0xcf91873b 0xcf91873b</textarea>
    <button id="convert">Convert</button>
    <textarea id="output"></textarea>