简体   繁体   English

在JavaScript中将float转换为32位十六进制字符串

[英]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. 我有一个表示gps坐标的浮点值,我喜欢将其转换为32位十六进制字符串。

I tried every solution described here but everytime, the result is not what I am expecting. 我尝试了这里描述的每个解决方案但每次,结果都不是我所期待的。

For example, most of the 'ToHex' functions : 例如,大多数'ToHex'功能:

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

returns me '2d.56d0b30b5aa8' 给我回复'2d.56d0b30b5aa8'

but I am expecting '42355b43' for result as most converters returns 但我期待'42355b43'的结果,因为大多数转换器返回

do you know how I could get '42355b43' as a result in JavaScript ? 你知道如何在JavaScript中获得'42355b43'吗?

Thank you ! 谢谢 !

You could take the TypedArray object with an ArrayBuffer and DataView . 您可以使用ArrayBufferDataView获取TypedArray对象。

Then set the value as float 32 and read the view as unsigned integer 8 bit for the values. 然后将值设置为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, { length: 4 }) .map((_, i) => getHex(view.getUint8(i))) .join(''); console.log(result); 

I finally decide to code my own function. 我最终决定编写自己的函数。 I post it here so it could help people : 我在这里发布它可以帮助人们:

function ToHex(d) {

    var sign = "0";

    if(d<0.0){
        sign = "1";
        d = -d;
    }

    var mantissa = parseFloat(d).toString(2);

    var exponent = 0;

    if(mantissa.substr(0,1) === "0"){
        exponent = mantissa.indexOf('.') - mantissa.indexOf('1') + 127;
    }
    else{
        exponent = mantissa.indexOf('.') - 1 + 127;
    }

    mantissa = mantissa.replace(".", "");
    mantissa = mantissa.substr(mantissa.indexOf('1')+1);

    if(mantissa.length>23){
        mantissa = mantissa.substr(0,23);
    }
    else{
        while(mantissa.length<23){
            mantissa = mantissa +"0";
        }
    }

    var exp = parseFloat(exponent).toString(2);

    while(exp.length<8){
        exp = "0" + exp;
    }

    var numberFull = sign + exp + mantissa;

    return parseInt(numberFull, 2).toString(16);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM