2

Like this :

I hava a float number 25.56,I could translate it to the four hexadecimal number E1 7A CC 41 in js.And the translate way is called as union in C.

But I don't know how to change the E1 7A CC 41 to the float in js

X Rene
  • 419
  • 2
  • 7
  • 1
    Can you show us what you have tried so far?? – m0bi5 Oct 24 '15 at 11:48
  • 2
    I think the OP meant something like `new Uint8ClampedArray(new Float32Array([25.56]).buffer)`. The expected result (`E1 7A CC 41`) can be seen like this: `Array.from(new Uint8ClampedArray(new Float32Array([25.56]).buffer)).map(function(a){return a.toString(16)})`. The other way around is also possible in JavaScript, but the duplicate target suggested by adeneo is incorrect. – Sebastian Simon Oct 24 '15 at 11:54

1 Answers1

2

You’ll have to work with typed arrays and array buffers:

Array.from(
  new Uint8ClampedArray(       // Represents the four bytes…
    new Float32Array([25.56])  // …of this number
      .buffer
  )
).map(function(a){
  return a.toString(16);
});

This returns the array [ "e1", "7a", "cc", "41" ].

The other way around works as well:

new Float32Array(
  new Uint8ClampedArray(
    ["e1", "7a", "cc", "41"].map(function(a){
      return parseInt(a, 16);
    })
  ).buffer
);

Note: This doesn’t quite return a Float32Aray with 25.56, but 25.559999465942383, because that’s all the precision you get with a 32 bit float number. With a Float64Array, you’d get the hex array ["8f", "c2", "f5", "28", "5c", "8f", "39", "40"] and then you’d get the number 25.56 back, precisely.

These APIs are only supported since Firefox 4, Chrome 7 and Internet Explorer 10.


The constructors Uint8ClampedArray and Float32Array can get a length as their argument, an array or an ArrayBuffer.

When they get an array, a new typed array is created from that array.

When they get an ArrayBuffer, a new typed array is created based on the contents of the buffer.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75