1

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);
}
bring2dip
  • 886
  • 2
  • 11
  • 22

2 Answers2

2

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.

Sebastien C.
  • 4,649
  • 1
  • 21
  • 32
  • thanks this works too. but which one do i choose @callahan's one or your? – bring2dip Jan 06 '14 at 11:50
  • Well this one is only a bit longer. You should just take the version that you like more to see in your code. – Callahan Jan 06 '14 at 11:51
  • 1
    @callahan's answer uses the Buffer object which doesn't seems to be a part of html5. If you're doing it in a browser, you should prefer my version. If you're using Node.js, his solution is better. – Sebastien C. Jan 06 '14 at 11:54
  • I will keep both."Looks like i have to call two of the functions randomly" – bring2dip Jan 06 '14 at 11:54
  • The node.js thing is a good point. Never coded javascript, did not think of that. – Callahan Jan 06 '14 at 11:56
0

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

Community
  • 1
  • 1
Callahan
  • 474
  • 1
  • 9
  • 22