1

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.

1

1 Answer 1

2

Found!

function WearToFloat(value)
{
    var buffer = new ArrayBuffer(4);
    var dataView = new DataView(buffer);
    dataView.setUint32(0, value, true);
    return dataView.getFloat32(0);
}
Sign up to request clarification or add additional context in comments.

1 Comment

You might need to set setUInt32 3rd parameter to true in order to switch endianness behaviour to "Little endian". Doc says, by default Big endian is assumed. Same goes for getFloat32 with its 2nd parameter. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.