Reputation: 885
I have this function in php that would convert hexadecimal to 32 float in php. How do you do it in Javascript
public static function hexTo32Float($val)
{
$packed=pack("H*",$val);
$reversedpac=strrev($packed);
$unpack=unpack( "f",$reversedpac);
return array_shift($unpack);
}
Upvotes: 1
Views: 827
Reputation: 4833
What about playing with TypedArray (that will only work with recent browsers) ?
var intData = Uint32Array(1);
intData[0] = parseInt("42458c14", 16);
var dataAsFloat = new Float32Array(intData.buffer);
var result = dataAsFloat[0];
// result == 49.38679504394531
EDIT (one year later ...) : It does seem that the result could depend on whether or not your CPU is big indian or little indian. Be careful when using this.
Upvotes: 2
Reputation: 474
After a complete BS answer try the following I found in the answer to this question:
var b = new Buffer(hexNumber, 'hex').readFloatBE(0)
.
edit: The fault was the usage of readFloatLE here.
For further explanation: The point here is that readFloatXX()
expects buffer contents as two's complement signed values. I guess readFloatLE
is the version for unsigned floats (could not find that in the docs, though).
Upvotes: 0