Is there any way I can read bytes of a float value in JS? What I need is to write a raw FLOAT or DOUBLE value into some binary format I need to make, so is there any way to get a byte-by-byte IEEE 754 representation? And same question for writing of course.
6 Answers
You can do it with typed arrays:
var buffer = new ArrayBuffer(4);
var intView = new Int32Array(buffer);
var floatView = new Float32Array(buffer);
floatView[0] = Math.PI
console.log(intView[0].toString(2)); //bits of the 32 bit float
Or another way:
var view = new DataView(new ArrayBuffer(4));
view.setFloat32(0, Math.PI);
console.log(view.getInt32(0).toString(2)); //bits of the 32 bit float
Not sure what browser support is like though

- 24,223
- 14
- 73
- 76

- 95,302
- 53
- 242
- 374
-
6Cool, TIL `Double` is called `Float64` in Javascript. I was looking for `DoubleArray` - to no avail - but `Float64Array` exists and looks useful to me – John Dvorak Mar 01 '13 at 07:28
-
2Note that this is *not* supported in IE9! – Qix - MONICA WAS MISTREATED Sep 17 '14 at 00:14
-
5It looks like you can use a `Uint8Array` (at least in Chrome) instead of the `Int32Array` to more easily get at individual bytes – Matt Thomas Apr 07 '17 at 19:42
-
1"""**[*The bit pattern that might be observed in an ArrayBuffer after a Number value has been stored into it is not necessarily the same as the internal representation of that Number value used by the ECMAScript implementation.](https://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types-number-type)***""" – Pacerier Apr 17 '17 at 18:40
-
@Pacerier: Not sure I understand the meaning of that statement - isn't the bit pattern by definition an internal representation (if perhaps not an IEEE754 representation)? Is the implication that the bit pattern can remain all zeros, and that the representation of the number can be stored elsewhere somehow? – Eric Apr 17 '17 at 18:43
-
@Eric, No idea man, its written in awful language. I guess after `view.setFloat32`, you can't count on `view.getInt32(0)` to return a fixed value across platforms. – Pacerier Aug 07 '17 at 00:59
-
I think that's just saying that while [`setFloat32` is required to use IEEE754](https://www.ecma-international.org/ecma-262/7.0/#sec-setvalueinbuffer), there is no requirement that the `Number` type is using IEEE754 under the hood, and there may be a conversion/rounding step – Eric Aug 07 '17 at 02:36
-
@Qix - I bet it doesn't work in IE6 either unfortunately. – bryc Apr 09 '18 at 08:24
-
2@bryc, Netscape Navigator support is also imperfect. – toriningen Aug 20 '18 at 00:15
I've created an expansion of Miloš's solution that should be a bit faster, assuming TypedArray
s are not an option of course (in my case I'm working with an environment where they're not available):
function Bytes2Float32(bytes) {
var sign = (bytes & 0x80000000) ? -1 : 1;
var exponent = ((bytes >> 23) & 0xFF) - 127;
var significand = (bytes & ~(-1 << 23));
if (exponent == 128)
return sign * ((significand) ? Number.NaN : Number.POSITIVE_INFINITY);
if (exponent == -127) {
if (significand == 0) return sign * 0.0;
exponent = -126;
significand /= (1 << 22);
} else significand = (significand | (1 << 23)) / (1 << 23);
return sign * significand * Math.pow(2, exponent);
}
Given an integer containing 4 bytes holding an IEEE-754 32-bit single precision float, this will produce the (roughly) correct JavaScript number value without using any loops.

- 14,854
- 11
- 100
- 103

- 3,109
- 1
- 33
- 46
-
1`if (significand == 0) return sign * 0.0;` - surely anything times zero is... zero? Does `-1 * 0.0` produce negative zero? – Nick Oct 22 '13 at 22:13
-
-
@Pacerier: My answer to another question should help with that: http://stackoverflow.com/a/16043259/2187548 – Haravikk Apr 18 '17 at 19:36
I had a similar problem, I wanted to convert any javascript number to a Buffer and then parse it back without stringifying it.
function numberToBuffer(num) {
const buf = new Buffer(8)
buf.writeDoubleLE(num, 0)
return buf
}
Use example:
// convert a number to buffer
const buf = numberToBuffer(3.14)
// and then from a Buffer
buf.readDoubleLE(0) === 3.14
This works on current Node LTS (4.3.1) and up. didn't test in lower versions.

- 2,952
- 21
- 23
-
1I can confirm that this also works on Node.js 0.10.40. With my old version of Node-RED (0.11.1) I obviously don't have access to Float32Array so your solution is the only one for me! I use 'new Buffer(array)' to create the Buffer from a 4 byte binary float array and buffer.readFloatBE(0) to retreive the float. – winne2 Jan 06 '17 at 16:47
-
Tested on Node.JS 10.15, this solution seems faster than using typed arrays. Obviously if you're not using Node.JS, you cannot use buffers. – Oren Jun 25 '19 at 11:27
Koolinc's snippet is good if you need a solution that powerful, but if you need it for limited use you are better off writing your own code. I wrote the following function for converting a string hex representation of bytes to a float:
function decodeFloat(data) {
var binary = parseInt(data, 16).toString(2);
if (binary.length < 32)
binary = ('00000000000000000000000000000000'+binary).substr(binary.length);
var sign = (binary.charAt(0) == '1')?-1:1;
var exponent = parseInt(binary.substr(1, 8), 2) - 127;
var significandBase = binary.substr(9);
var significandBin = '1'+significandBase;
var i = 0;
var val = 1;
var significand = 0;
if (exponent == -127) {
if (significandBase.indexOf('1') == -1)
return 0;
else {
exponent = -126;
significandBin = '0'+significandBase;
}
}
while (i < significandBin.length) {
significand += val * parseInt(significandBin.charAt(i));
val = val / 2;
i++;
}
return sign * significand * Math.pow(2, exponent);
}
There are detailed explanations of algorithms used to convert in both directions for all formats of floating points on wikipedia, and it is easy to use those to write your own code. Converting from a number to bytes should be more difficult because you need to normalize the number first.

- 2,229
- 5
- 24
- 43
-
2I've expanded this solution to handle 64-bit floats and little-endian encoding. It also takes an array of bytes instead of a base-16 string (so that 64-bit floats work fine without rounding issues). https://gist.github.com/2192799 – Katelyn Gadd Mar 25 '12 at 10:53
Would this snippet help?
var parser = new BinaryParser
,forty = parser.encodeFloat(40.0,2,8)
,twenty = parser.encodeFloat(20.0,2,8);
console.log(parser.decodeFloat(forty,2,8).toFixed(1)); //=> 40.0
console.log(parser.decodeFloat(twenty,2,8).toFixed(1)); //=> 20.0
-
6The algorithm used in that snippet is thoroughly broken. It fails on particular values when used to read floats or doubles. For example, it reads 40.0 as 32.0, and 20.0 as 16.0. – Katelyn Gadd Mar 25 '12 at 10:38
-
2
-
6Do not use this BinaryParser class! It is *not* strict compliant (it uses `with`)! – Qix - MONICA WAS MISTREATED Sep 17 '14 at 00:11
64-bit IEEE 754 float to its binary representation and back:
// float64ToOctets(123.456) -> [64, 94, 221, 47, 26, 159, 190, 119]
function float64ToOctets(number) {
const buffer = new ArrayBuffer(8);
new DataView(buffer).setFloat64(0, number, false);
return [].slice.call(new Uint8Array(buffer));
}
// octetsToFloat64([64, 94, 221, 47, 26, 159, 190, 119]) -> 123.456
function octetsToFloat64(octets) {
const buffer = new ArrayBuffer(8);
new Uint8Array(buffer).set(octets);
return new DataView(buffer).getFloat64(0, false);
}
// intToBinaryString(8) -> "00001000"
function intToBinaryString(i, length) {
return i.toString(2).padStart(8, "0");
}
// binaryStringToInt("00001000") -> 8
function binaryStringToInt(b) {
return parseInt(b, 2);
}
function octetsToBinaryString(octets) {
return octets.map((i) => intToBinaryString(i)).join("");
}
function float64ToBinaryString(number) {
return octetsToBinaryString(float64ToOctets(number));
}
function binaryStringToFloat64(string) {
return octetsToFloat64(string.match(/.{8}/g).map(binaryStringToInt));
}
console.log(float64ToBinaryString(123.123))
console.log(binaryStringToFloat64(float64ToBinaryString(123.123)))
console.log(binaryStringToFloat64(float64ToBinaryString(123.123)) === 123.123)
This is a slightly modified version this MIT-licensed code: https://github.com/bartaz/ieee754-visualization/blob/master/src/ieee754.js

- 14,854
- 11
- 100
- 103