javascriptnode.jsbufferarraybuffer

Buffer + writeUInt32LE from NodeJS to Javascript


So I have this function, comming from a NodeJS script:

function WearToFloat(value)
{
    buf = new Buffer(4);
    buf.writeUInt32LE(+value, 0);
    return buf.readFloatLE(0).toString();
}

and I need to translate this in pure Javascript that can be read by any web browser.

Unfortunately, I have absolutely no knowledge in NodeJS nor buffers in JS, and can't figure out with docs.

The aim of this function is to convert a value that looks like 1054356424 into a float number from 0 to 1 (in this case, 0.4222700595855713)

Any clue?

Edit: Seems that the same kind of question has been asked here but only using a library, and I don't want to load a full library just for that, there must be a simple way to convert this NodeJS function into a Javascript one.


Solution

  • Found!

    function WearToFloat(value)
    {
        var buffer = new ArrayBuffer(4);
        var dataView = new DataView(buffer);
        dataView.setUint32(0, value, true);
        return dataView.getFloat32(0);
    }