Parse HEX float

不羁的心 提交于 2019-12-05 11:24:24

The above answer is no longer valid. Buffer has been deprecated (see https://nodejs.org/api/buffer.html#buffer_new_buffer_size).

New Solution:

function numToFloat32Hex(v,le)
{
    if(isNaN(v)) return false;
    var buf = new ArrayBuffer(4);
    var dv  = new DataView(buf);
    dv.setFloat32(0, v, true);
    return ("0000000"+dv.getUint32(0,!(le||false)).toString(16)).slice(-8).toUpperCase();
}

For example:

numToFloat32Hex(4060,true) // returns "00C07D45"
numToFloat32Hex(4060,false) // returns "457DC000"

Tested in Chrome and Firefox

If you want a hex string, try this:

> var b = new Buffer(4);
> b.writeFloatLE(4060, 0)
> b.toString('hex')
'00c07d45'

And the other way (using your input):

> Buffer('34C87D45', 'hex').readFloatLE(0)
4060.5126953125

UPDATE: new Buffer(size) has been deprecated, but it's easily replaced by Buffer.alloc(size):

var b = Buffer.alloc(4);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!