double to float integer bits
Transform JS number (double) to float value and receive the integer bits of it
by phip1611
HTML
See browser console
JavaScript
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));