代码之家  ›  专栏  ›  技术社区  ›  nornagon

JavaScript中ieee754浮点数的编码与解码

  •  8
  • nornagon  · 技术社区  · 14 年前

    我需要编码和解码ieee754浮点和双倍从二进制在节点.js解析网络协议。

    是否有任何现有的库可以这样做,或者我必须阅读规范并自己实现它?或者我应该写一个C模块来实现它?

    4 回复  |  直到 14 年前
        1
  •  3
  •   Pointy    12 年前

    请注意,从node 0.6开始,此功能就包含在核心库中,因此这是实现此功能的最佳新方法。

    http://nodejs.org/docs/latest/api/buffer.html 详情。

    https://github.com/dobesv/node-binstruct

        2
  •  1
  •   Janus Troelsen    12 年前

    我移植了一个C++(用GNU-GMP)转换器,用Voal128支持Emscripten,以便它在浏览器中运行: https://github.com/ysangkok/ieee-754

        3
  •  0
  •   phip1611    4 年前

    在现代JavaScript(ECMAScript 2015)中,您可以使用 ArrayBuffer Float32Array / Float64Array

    // 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];
    

    注:这在NodeJS中也适用,但在Chrome、Firefox和Edge中也适用。