javascriptbufferfloat32

JavaScript Buffer to Float32


I am receiving a Buffer 40 48 f5 c3 3f b4 7a e1 3f 35 c2 8f with the following values, the values are coded as Float32 :

3.14: 0x4048f5c3
1.41: 0x3fb47ae1
0.71: 0x3f35c28f

Can I map the buffer into a json as a row of numbers:

{
  value1: 3.14,
  value2: 1.41,
  value3: 0.71,
}

or into a Array as numbers [3.14, 1.41, 0.71]


Solution

  • My solution from an existing answer from another question:

    For decoding a float coded in Big Endian (ABCD) with Node.js:

    const buffer = [
      0x40, 0x48, 0xf5, 0xc3,
      0x3f, 0xb4, 0x7a, 0xe1,
      0x3f, 0x35, 0xc2, 0x8f];
    
    const firstValue = Buffer.from(buffer).readFloatBE(0); // 3.14
    const secondValue = Buffer.from(buffer).readFloatBE(4) // 1.41
    const thirdValue = Buffer.from(buffer).readFloatBE(8) // 0.71