9

I need to encode and decode IEEE 754 floats and doubles from binary in node.js to parse a network protocol.

Are there any existing libraries that do this, or do I have to read the spec and implement it myself? Or should I write a C module to do it?

nornagon
  • 15,393
  • 18
  • 71
  • 85
  • See also: [javascript - Read/Write bytes of float in JS - Stack Overflow](https://stackoverflow.com/q/4414077/5267751) (all the answers there would work here too) – user202729 Jan 30 '21 at 10:55
  • Maybe you can see if this thing does what you want: http://jsfromhell.com/classes/binary-parser – Tor Valamo Sep 18 '10 at 20:39

3 Answers3

3

Note that as of node 0.6 this functionality is included in the core library, so that is the new best way to do it.

See http://nodejs.org/docs/latest/api/buffer.html for details.

If you are reading/writing binary data structures you might consider using a friendly wrapper around this functionality to make things easier to read and maintain. Plug follows: https://github.com/dobesv/node-binstruct

Pointy
  • 405,095
  • 59
  • 585
  • 614
Dobes Vandermeer
  • 8,463
  • 5
  • 43
  • 46
2

In modern JavaScript (ECMAScript 2015) you can use ArrayBuffer and Float32Array/Float64Array. I solved it like this:

// 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: This works in NodeJS but also in Chrome, Firefox, and Edge.

phip1611
  • 5,460
  • 4
  • 30
  • 57
1

I ported a C++ (made with GNU GMP) converter with float128 support to Emscripten so that it would run in the browser: https://github.com/ysangkok/ieee-754

Emscripten produces JavaScript that will run on Node.js too. You will get the float representation as a string of bits, though, I don't know if that's what you want.

Janus Troelsen
  • 20,267
  • 14
  • 135
  • 196