Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert float to 32bit hex string in JavaScript

I have a float value representing gps coordinates and I liked to convert it to a 32bit hex string.

I tried every solution described here but everytime, the result is not what I am expecting.

For example, most of the 'ToHex' functions :

var lat = 45.839152;
console.log(ToHex(lat));

returns me '2d.56d0b30b5aa8'

but I am expecting '42355b43' for result as most converters returns

do you know how I could get '42355b43' as a result in JavaScript ?

Thank you !

like image 393
Aznhar Avatar asked Nov 07 '17 18:11

Aznhar


Video Answer


1 Answers

You could take the TypedArray object with an ArrayBuffer and DataView.

Then set the value as float 32 and read the view as unsigned integer 8 bit for the values.

const getHex = i => ('00' + i.toString(16)).slice(-2);

var view = new DataView(new ArrayBuffer(4)),
    result;

view.setFloat32(0, 45.839152);

result = Array
    .apply(null, { length: 4 })
    .map((_, i) => getHex(view.getUint8(i)))
    .join('');

console.log(result);
like image 159
Nina Scholz Avatar answered Nov 14 '22 21:11

Nina Scholz