javascript - 将 float 重新解释为整数

标签 javascript casting floating-point integer typed-arrays

这个问题可能是“不寻常的”,但我需要将 float Number 转换为整数 Number,而不修改其二进制表示形式。

例如, float 37.5 由字节 0x42160000 表示(根据 IEEE 754)。 我需要将 0x42160000 重新解释为整数,即数字 1108738048

我该怎么做?我在想可能有一些按位技巧来实现这一点?

明确地说,我不是在寻找Math.roundparseInt

最佳答案

Typed arrays可以在这里派上用场:http://jsfiddle.net/rtYrM/ .

// create array which is specialized for holding 1 float value
var floatArray = new Float32Array(1);

// set the float value
floatArray[0] = 37.5;

// use its buffer (4 bytes for 1 float) and pass it to an array
// specialized for integers
var intArray = new Int32Array(floatArray.buffer);

// the integer array will interpret the buffer bytes as an integer,
// which seems to be just what you want
intArray[0] === 1108738048; //true

intArray.buffer 将保存与 floatArray.buffer 相同的字节,但是通过不使用缓冲区而是使用数组本身访问它,它将读取这些字节作为类型化数组指定的类型:Int32Array 为整数,Float32Array 为 float 。

在这种情况下(以 10 为基数):

  • floatArray 设置为值 [ 37.5 ]
  • floatArray.buffer 自动设置为值 [ 0, 0, 22, 66 ]
  • floatArray.buffer 被传递给一个新的整数数组,intArray
  • intArray.buffer 因此也包含值 [ 0, 0, 22, 66 ]
  • intArray 包含值 [ 1108738048 ],使用其缓冲区计算。

关于javascript - 将 float 重新解释为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7538734/

相关文章:

javascript - Bootstrap 3.0 : added 2 sliders to home page both conflicting

JavaScript 继承(使用父类(super class)函数时无限循环)

javascript - 当我点击 html5 中的图像时,播放视频时控件不起作用?

c++ - 查找浮点计数器的最大值

Java float 说明

javascript - CSS/JavaScript : get user-visible text of an element

java - 动态类型检查匹配类型参数

c# - 在 C# 和 VB.NET 中自动转换为字符串

c++ - 如何在 Xcode 中构建没有 calloc 转换结果的程序?

c++ - 如何检查 C++ 编译器是否使用 IEEE 754 浮点标准