将 javascript 数字转换为浮点数(单精度 IEEE-754)并接收整数位

Convert javascript number to float (single precision IEEE-754) and receive integer bits

我想将 javascript 数字截断为单精度(浮点数)并接收整数位。我该怎么做?

例如:“5”在 IEEE-754 @ 32 位中是 0x40a00000。我想在 Javascript.

中进行 5 => 0x40a00000 映射

此解决方案需要 ES2015 才能在现代浏览器和 NodeJS 中运行。

Javascript 数字是双精度数(IEEE-754 @ 64 位/双精度)。使用 Float32Array 我们可以将 f64(double)值截断为 f32(float)表示。使用 Uint32Array 我们可以在之后提取原始整数位。

JSFiddle 上的代码:https://jsfiddle.net/phip1611/u5b4ozks/19/

作为堆栈代码段:

// 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));

您可以根据这个简洁的在线工具验证输出:https://www.h-schmidt.net/FloatConverter/IEEE754.html