在JavaScript中将float转换为32位十六进制字符串 [英] Convert float to 32bit hex string in JavaScript

查看:248
本文介绍了在JavaScript中将float转换为32位十六进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代表gps坐标的浮点值,我喜欢将它转换为一个32位的十六进制字符串。



我试过每个解决方案 $ b
$ b

例如,大部分'ToHex'函数:

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

返回我'2d.56d0b30b5aa8'



但我预计'42355b43'的结果为大多数转换器返回



你知道我如何在JavaScript中获得'42355b43'吗?



谢谢!

解决方案

您可以将 TypedArray 对象与 ArrayBuffer DataView 。然后将值设置为float 32并将视图读为无符号整数8位数据。



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 ,(长度:4)).map((_,i)=> getHex(view.getUint8(i))).join(''); console.log(result); / pre>


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 !

解决方案

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);

这篇关于在JavaScript中将float转换为32位十六进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆