在JavaScript中编码和解码IEEE 754浮点数

9

我需要在node.js中将IEEE 754浮点数和双精度浮点数从二进制编码解码以解析网络协议。

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


1
也许你可以看看这个东西是否符合你的需求:http://jsfromhell.com/classes/binary-parser - Tor Valamo
参见:javascript - Read/Write bytes of float in JS - Stack Overflow(那里的所有答案在这里也适用)。 - user202729
3个回答

3

2
在现代JavaScript(ECMAScript 2015)中,您可以使用ArrayBufferFloat32Array/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];

PS:这适用于NodeJS,同时也适用于Chrome、Firefox和Edge。


1
我将一个支持float128的C++转换器(使用GNU GMP制作)移植到Emscripten,以便在浏览器中运行:https://github.com/ysangkok/ieee-754
Emscripten生成的JavaScript也可以在Node.js上运行。但是,您将得到表示为位字符串的浮点数,我不知道这是否符合您的要求。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接