Reputation: 303224
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
. The bytes were generated using Ruby's Array#pack method like:
[100.32].pack('g') # "\x42\xC8\xA3\xD7"
Using the npm binary
package I can decode these bytes as a 32-bit unsigned integer:
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
?
Upvotes: 0
Views: 606
Reputation: 106696
It looks like it's stored as a float, which is 32-bit. 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.
Upvotes: 2