Skip to content Skip to sidebar Skip to footer

Read/write Bytes Of Float In Js

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 b

Solution 1:

You can do it with typed arrays:

var buffer = newArrayBuffer(4);
var intView = newInt32Array(buffer);
var floatView = newFloat32Array(buffer);

floatView[0] = Math.PIconsole.log(intView[0].toString(2)); //bits of the 32 bit float

Or another way:

var view = newDataView(newArrayBuffer(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

Solution 2:

I've created an expansion of Milos' solution that should be a bit faster, assuming TypedArrays are not an option of course (in my case I'm working with an environment where they're not available):

functionBytes2Float32(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.

Solution 3:

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:

functiondecodeFloat(data) {
    varbinary = 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)
            return0;
        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.

Solution 4:

I had a similar problem, I wanted to convert any javascript number to a Buffer and then parse it back without stringifying it.

functionnumberToBuffer(num) {
  const buf = newBuffer(8)
  buf.writeDoubleLE(num, 0)
  return buf
}

Use example:

// convert a number to bufferconst 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.

Solution 5:

Would this snippet help?

var parser = newBinaryParser
  ,forty = parser.encodeFloat(40.0,2,8) 
  ,twenty = parser.encodeFloat(20.0,2,8);  
console.log(parser.decodeFloat(forty,2,8).toFixed(1));   //=> 40.0console.log(parser.decodeFloat(twenty,2,8).toFixed(1));  //=> 20.0

Post a Comment for "Read/write Bytes Of Float In Js"