问题
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.
回答1:
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
回答2:
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);
来源:https://stackoverflow.com/questions/16612520/parse-hex-float