Node.js’s Buffer.writeFloatBE in Javascript

The following code does float to integer converting like so:

var buffer = new Buffer(4);
buffer.writeFloatBE(number, 0);
return -~parseInt(buffer.toString('hex'), 16) - 1;

and its output is like so

(float)0.05 = (int)1028443341       
(float)-0.05 = (int)-1119040307
(float)0.1  = (int)1036831949       
(float)-0.1  = (int)-1110651699
(float)0.2  = (int)1045220557       
(float)-0.2  = (int)-1102263091
(float)0.5  = (int)1056964608       
(float)-0.5  = (int)-1090519040

How can I reverse this code, insert integer (1056964608) and return a float?

Answer

We could literally revert each operation one by one and end up with the following code:

var hexString = (~-(number + 1)).toString(16);
return new Buffer(hexString, 'hex').readFloatBE();

This would work fine on positive floats, so we should take some extra care for negative ones.

From the answer by @PleaseStand:

Tilde operator removes everything after the decimal point because the bitwise operators implicitly convert their operands to signed 32-bit integers.

If x is no between -(231) and 231 – 1 overflow will occur and the number will “wrap around”.

> floatToBin(0.05)
'11 1101 0100 1100 1100 1100 1100 1101'

> floatToBin(-0.05)
'1011 1101 0100 1100 1100 1100 1100 1101'

So, the final function would look like this:

function intToFloat(number) {
    number = ~-(number + 1);

    if (number < 0) {
        number += Math.pow(2, 32);
    }

    var float = new Buffer(number.toString(16), 'hex').readFloatBE();

    const significantDigits = 5;
    return parseFloat(float.toFixed(significantDigits));
}

Leave a Reply

Your email address will not be published. Required fields are marked *