我需要在node.js中将IEEE 754浮点数和双精度浮点数从二进制编码解码以解析网络协议。
是否有现有的库可以完成这个任务,或者我必须阅读规范并自己实现?或者我应该编写一个C模块来完成它?
我需要在node.js中将IEEE 754浮点数和双精度浮点数从二进制编码解码以解析网络协议。
是否有现有的库可以完成这个任务,或者我必须阅读规范并自己实现?或者我应该编写一个C模块来完成它?
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];
PS:这适用于NodeJS,同时也适用于Chrome、Firefox和Edge。