最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Parse HEX float - Stack Overflow

programmeradmin1浏览0评论

I have integer, for example, 4060.

How I can get HEX float (\x34\xC8\x7D\x45) from it?

JS hasn't float type, so I don't know how to do this conversion.

Thank you.

I have integer, for example, 4060.

How I can get HEX float (\x34\xC8\x7D\x45) from it?

JS hasn't float type, so I don't know how to do this conversion.

Thank you.

Share Improve this question edited May 17, 2013 at 15:57 robertklep 204k37 gold badges414 silver badges404 bronze badges asked May 17, 2013 at 15:14 user0103user0103 1,2723 gold badges18 silver badges36 bronze badges 2
  • 1 I think I'm missing something obvious, but you have an integer; there is no decimal portion (except an implicit 0). What are you trying to do? – David Thomas Commented May 17, 2013 at 15:17
  • 1 Anyone who voted for "duplicate", please learn about IEEE 754 formats...voted to reopen. – robertklep Commented May 17, 2013 at 16:48
Add a ment  | 

2 Answers 2

Reset to default 7

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);

The above answer is no longer valid. Buffer has been deprecated (see https://nodejs/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

发布评论

评论列表(0)

  1. 暂无评论