[英]Convert 4 binary bytes as single-precision float to Number
I have a single-precision, big-endian floating point number stored in 4 binary bytes that I'd like to decode into a JS Number
. 我有一个单精度的big-endian浮点数,存储在4个二进制字节中,我想将其解码为JS Number
。 The bytes were generated using Ruby's Array#pack method like: 这些字节是使用Ruby的Array#pack方法生成的,例如:
[100.32].pack('g') # "\x42\xC8\xA3\xD7"
Using the npm binary
package I can decode these bytes as a 32-bit unsigned integer: 使用npm binary
包,我可以将这些字节解码为32位无符号整数:
let binary = require('binary'); // npm install binary
let buf = new Buffer([0x42,0xc8,0xa3,0xd7]);
let val = binary.parse(buf).word32bu('foo').vars.foo;
console.log(val);
// 1120445399
…but that doesn't help me. …但这对我没有帮助。 How can I convert either 1120445399
or [0x42,0xc8,0xa3,0xd7]
into the floating point number 100.32
? 如何将1120445399
或[0x42,0xc8,0xa3,0xd7]
转换为浮点数100.32
?
It looks like it's stored as a float, which is 32-bit. 看起来它存储为32位浮点数。 Node can already handle these common number parsing/writing scenarios. 节点已经可以处理这些常见的数字解析/写入方案。 In this particular case, you can just use buf.readFloatBE(0)
to convert the 4 bytes. 在这种情况下,您可以只使用buf.readFloatBE(0)
转换这4个字节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.