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.
Take decimal number as dividend. Divide this number by 16 (16 is base of hexadecimal so divisor here). Store the remainder in an array (it will be: 0 to 15 because of divisor 16, replace 10, 11, 12, 13, 14, 15 by A, B, C, D, E, F respectively). Repeat the above two steps until the number is greater than zero.
To convert a hex value into a decimal value, we multiply each “position” in the hex sequence by 16 raised to a power. Working from right to left, we know that furthest-right position is 16^0 (so, just a 1). The second-from-right position is 16^1 (so, just a 16).
Given hexadecimal number is 7CF. To convert this into a decimal number system, multiply each digit with the powers of 16 starting from units place of the number. From this, the rule can be defined for the conversion from hex numbers to decimal numbers.
Example − Convert binary number 1101010 into hexadecimal number. First convert this into decimal number: = (1101010)2 = 1x26+1x25+0x24+1x23+0x22+1x21+0x20 = 64+32+0+8+0+2+0 = (106)10 Then, convert it into hexadecimal number = (106)10 = 6x161+10x160 = (6A)16 which is answer.
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.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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With