5

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.

robertklep
  • 198,204
  • 35
  • 394
  • 381
user0103
  • 1,246
  • 3
  • 18
  • 36
  • 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 May 17 '13 at 15:17
  • 1
    Anyone who voted for "duplicate", please learn about IEEE 754 formats...voted to reopen. – robertklep May 17 '13 at 16:48

2 Answers2

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);
robertklep
  • 198,204
  • 35
  • 394
  • 381
2

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

user2871305
  • 1,052
  • 1
  • 8
  • 7