I want to truncate a javascript number to single precision (float) and receive the integer bits. How can I do this?
For example: "5" is 0x40a00000
in IEEE-754 @ 32 bit. I want to do the 5 => 0x40a00000
mapping in Javascript.
This solution needs ES2015 to work and works in modern browsers and NodeJS.
Javascript numbers are doubles (IEEE-754 @ 64bit / double precision). With Float32Array
we can truncate a f64 (double) value into a f32 (float) representation. With Uint32Array
we can extract the raw integer bits afterwards.
Code on JSFiddle: https://jsfiddle.net/phip1611/u5b4ozks/19/
And as a Stack Snippet:
// double is "number" (javascript data type)
function jsF64ToF32IntegerBitsStr(double) {
// float / f32 has 32 bit => 4 bytes
const BYTES = 4;
// Buffer is like a raw view into memory
const buffer = new ArrayBuffer(BYTES);
// Float32Array: interpret bytes in the memory as f32 (IEEE-754) bits
const float32Arr = new Float32Array(buffer);
// UInt32Array: interpret bytes in the memory as unsigned integer bits.
// Important that we use unsigned here, otherwise the MSB would be interpreted as sign
const uint32Array = new Uint32Array(buffer);
// will convert double to float during assignment
float32Arr[0] = double;
// now read the same memory as unsigned integer value
const integerValue = uint32Array[0];
// to hex string
const integerBitsHex = integerValue.toString(16);
// + hex prefix
return '0x' + integerBitsHex;
}
// '0x40a00000'
console.log('5 in IEEE-754 single precision is: ', jsF64ToF32IntegerBitsStr(5));
// '0xc0490625'
console.log('-3.141 in IEEE-754 single precision is: ', jsF64ToF32IntegerBitsStr(-3.141));
// '0x7fffffff'
console.log('NaN in IEEE-754 single precision is: ', jsF64ToF32IntegerBitsStr(NaN));
You can verify the output against this neat online tool: https://www.h-schmidt.net/FloatConverter/IEEE754.html