简体   繁体   English

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

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

I want to truncate a javascript number to single precision (float) and receive the integer bits.我想将 javascript 数字截断为单精度(浮点)并接收 integer 位。 How can I do this?我怎样才能做到这一点?

For example: "5" is 0x40a00000 in IEEE-754 @ 32 bit.例如:“5”是 IEEE-754 @ 32 位中的0x40a00000 I want to do the 5 => 0x40a00000 mapping in Javascript.我想在 Javascript 中进行 5 => 0x40a00000映射。

This solution needs ES2015 to work and works in modern browsers and NodeJS.该解决方案需要 ES2015 才能在现代浏览器和 NodeJS 中运行。

Javascript numbers are doubles (IEEE-754 @ 64bit / double precision). Javascript 数字是双精度数(IEEE-754 @ 64 位/双精度)。 With Float32Array we can truncate a f64 (double) value into a f32 (float) representation.使用Float32Array ,我们可以将 f64(双精度)值截断为 f32(浮点)表示。 With Uint32Array we can extract the raw integer bits afterwards.使用Uint32Array ,我们可以提取原始的 integer 位。

Code on JSFiddle: https://jsfiddle.net/phip1611/u5b4ozks/19/ 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您可以根据这个简洁的在线工具验证 output: https://www.h-schmidt.net/FloatConverter/IEEE754.ZFC35FDC70D5FC69D269883A822C7A53E

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM