Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding and decoding IEEE 754 floats in JavaScript

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?

like image 214
nornagon Avatar asked Sep 18 '10 08:09

nornagon


3 Answers

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

like image 108
Dobes Vandermeer Avatar answered Sep 21 '22 17:09

Dobes Vandermeer


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.

like image 28
Janus Troelsen Avatar answered Sep 23 '22 17:09

Janus Troelsen


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.

like image 37
phip1611 Avatar answered Sep 23 '22 17:09

phip1611