Reputation: 467
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
Upvotes: 2
Views: 418
Reputation: 19485
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.
Upvotes: 2