Parse hex float

I have an integer, for example 4060 .

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

JS does not have a float type, so I do not know how to do this.

Thanks.

+4
source share
2 answers

The above answer is no longer valid. Buffer 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 instance:

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

Tested in Chrome and Firefox

+1
source

If you want to use a hexadecimal string, try the following:

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

And in another way (using your input):

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

UPDATE : new Buffer(size) deprecated, but it is easy to replace it with Buffer.alloc(size) :

 var b = Buffer.alloc(4); 
+7
source

Source: https://habr.com/ru/post/1481416/


All Articles