Sergei G Sergei G - 6 months ago 47
Javascript Question

Converting IEEE 754 from bit stream into float in JavaScript

I have serialized 32-bit floating number using GO language function (math.Float32bits) which returns the floating point number corresponding to the IEEE 754 binary representation. This number is then serialized as 32-bit integer and is read into java script as byte array.

For example, here is actual number:

float: 2.8088086
as byte array: 40 33 c3 85
as hex: 0x4033c385


There is a demo converter that displays the same numbers.

I need to get that same floating number back from byte array in JavaScript and I have no idea how to do that.

Answer

Given the data you've described:

var buffer = new ArrayBuffer(4);
var bytes = new Uint8Array(buffer);
bytes[0] = 0x40;
bytes[1] = 0x33;
bytes[2] = 0xc3;
bytes[3] = 0x85;    

We can retrieve the value as a floating-point number using a DataView:

var view = new DataView(buffer);
// If you only had a Uint8Array, you would use bytes.buffer instead of buffer.

console.log(view.getFloat32(0, false));
2.8088085651397705

var buffer = new ArrayBuffer(4);
var bytes = new Uint8Array(buffer);
bytes[0] = 0x40;
bytes[1] = 0x33;
bytes[2] = 0xc3;
bytes[3] = 0x85;    

var view = new DataView(buffer);

console.log(view.getFloat32(0, false));