Encoding and decoding IEEE 754 floats in JavaScript

前端 未结 5 761
故里飘歌
故里飘歌 2021-01-05 04:29

I need to encode and decode IEEE 754 floats and doubles from binary in node.js to parse a network protocol.

Are there any existing libraries that do this, or do I ha

5条回答
  •  孤街浪徒
    2021-01-05 05:18

    In modern JavaScript (ECMAScript 2015) you can use ArrayBuffer and Float32Array/Float64Array. I solved it like this:

    // 0x40a00000 is "5" in float/IEEE-754 32bit.
    // You can check this here: https://www.h-schmidt.net/FloatConverter/IEEE754.html
    // MSB (Most significant byte) is at highest index
    const bytes = [0x00, 0x00, 0xa0, 0x40];
    // The buffer is like a raw view into memory.
    const buffer = new ArrayBuffer(bytes.length);
    // The Uint8Array uses the buffer as its memory.
    // This way we can store data byte by byte
    const byteArray = new Uint8Array(buffer);
    for (let i = 0; i < bytes.length; i++) {
      byteArray[i] = bytes[i];
    }
    
    // float array uses the same buffer as memory location
    const floatArray = new Float32Array(buffer);
    
    // floatValue is a "number", because a number in javascript is a
    // double (IEEE-754 @ 64bit) => it can hold f32 values
    const floatValue = floatArray[0];
    
    // prints out "5"
    console.log(`${JSON.stringify(bytes)} as f32 is ${floatValue}`);
    
    // double / f64
    // const doubleArray = new Float64Array(buffer);
    // const doubleValue = doubleArray[0];
    

    PS: This works in NodeJS but also in Chrome, Firefox, and Edge.

提交回复
热议问题