Encoding and decoding IEEE 754 floats in JavaScript

前端 未结 5 762
故里飘歌
故里飘歌 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:10

    Note that as of node 0.6 this functionality is included in the core library, so that is the new best way to do it.

    See http://nodejs.org/docs/latest/api/buffer.html for details.

    If you are reading/writing binary data structures you might consider using a friendly wrapper around this functionality to make things easier to read and maintain. Plug follows: https://github.com/dobesv/node-binstruct

    0 讨论(0)
  • 2021-01-05 05:18

    I ported a C++ (made with GNU GMP) converter with float128 support to Emscripten so that it would run in the browser: https://github.com/ysangkok/ieee-754

    Emscripten produces JavaScript that will run on Node.js too. You will get the float representation as a string of bits, though, I don't know if that's what you want.

    0 讨论(0)
  • 2021-01-05 05:18

    Maybe you can see if this thing does what you want: http://jsfromhell.com/classes/binary-parser

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-05 05:33

    This is the best way to do it: http://github.com/pgriess/node-jspack (perhaps if you need to do things on node < 0.6.)

    0 讨论(0)
提交回复
热议问题