Search code examples
javascriptieee-754

Javascript - Convert hex to IEEE-754 32-bit single precision


I'm trying to convert the following hex string: "42AA4000" to 85.125 (float-32)

I'm try modify code from Řrřola REF.

this my code (don't work)

function hex_to_number(str) {
  // Pad the string with zeroes to 16 characters.
  // You can omit this if you control your inputs.
  str = (str + "0000000000000000").slice(0,16);

  // Split into bits: sign (1), exponent (11), significand (52).
  var sign_and_exponent_bits = parseInt(str.slice(0,3), 16);
  var sign = sign_and_exponent_bits >= 0x100 ? -1 : +1;
  var exponent_bits = sign_and_exponent_bits & ((1<<8) - 1);
  var significand_bits = parseInt(str.slice(3,16), 16);

  // Classify the floating-point value.
  if (exponent_bits == 0x0FF)  // infinity | not a number
    return significand_bits == 0 ? sign * Number.POSITIVE_INFINITY : Number.NaN;
  else if (exponent_bits == 0)  // zero | subnormal number
    return sign * Math.pow(2, 1-127-23) * significand_bits;
  else  // normal number
    return sign * Math.pow(2, exponent_bits-127-23) * (Math.pow(2, 23) + significand_bits);
}

How can I get a javascript function that gives me the answer I need? Thank you.


Solution

  • You don't need any external code for this - use a DataView:

    const dv = new DataView(new ArrayBuffer(4));
    dv.setUint32(0, 0x42AA4000);
    let output = dv.getFloat32(0);
    
    console.log(output);

    More details on the DataView object is available at MDN