Aznhar
Aznhar

Reputation: 606

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 !

Upvotes: 8

Views: 7505

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386570

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

Upvotes: 12

Aznhar
Aznhar

Reputation: 606

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

Upvotes: 0

Related Questions