将浮点数重新解释为整数
这个问题可能是“不寻常的”,但我需要将浮点 Number
转换为整数 Number
,而不修改其二进制表示形式。
例如,浮点数 37.5
由字节 0x42160000
表示(根据 IEEE 754)。 我需要将 0x42160000
重新解释为整数,即数字 1108738048
我该怎么做?我在想可能有一些按位技巧来实现这一点?
需要明确的是,我不是在寻找Math.round
或parseInt
。
This question is probably "unusual", but I need to cast a float Number
to an integer Number
, without modifying its binary representation.
For example, the float 37.5
is represented by the bytes 0x42160000
(according to IEEE 754).
I need to reinterpret 0x42160000
as an integer, i.e. the number 1108738048
How do I do this? I'm thinking there could be some bitwise tricks to accomplish this?
To be clear, I'm not looking for Math.round
or parseInt
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
类型化数组在这里可以派上用场:http://jsfiddle.net/rtYrM/。
intArray.buffer
将保存与floatArray.buffer
相同的字节,但通过不使用缓冲区而是使用数组本身访问它,它将按照指定的类型读取这些字节通过类型化数组:Int32Array
为整数,Float32Array
为浮点数。在本例中(以 10 为基数):
floatArray
设置为值[ 37.5 ]
。floatArray.buffer
自动设置为值[ 0, 0, 22, 66 ]
。floatArray.buffer
被传递给一个新的整数数组intArray
。intArray.buffer
也包含值[ 0, 0, 22, 66 ]
。intArray
包含使用其缓冲区计算的值[ 1108738048 ]
。Typed arrays can come in handy here: http://jsfiddle.net/rtYrM/.
intArray.buffer
will hold the same bytes asfloatArray.buffer
, but by not accessing it with the buffer but with the array itself, it will read those bytes as the type specified by the typed array: as integers forInt32Array
, and as floats forFloat32Array
.In this case (in base 10):
floatArray
is set to the value[ 37.5 ]
.floatArray.buffer
is automatically set to the values[ 0, 0, 22, 66 ]
.floatArray.buffer
is passed to a new integer array,intArray
.intArray.buffer
therefore contains the values[ 0, 0, 22, 66 ]
as well.intArray
contains the value[ 1108738048 ]
, calculated with its buffer.我不相信 Javascript 包含任何执行此操作的机制。 Java 中有一个方法
java.lang.Float.floatBitsToIntBits()
,因此根据您的预期环境,您也许可以使用它。如果所有其他方法都失败,您可能必须将数据发送回服务器进行转换。另外,我也见过用 Javascript 方法进行这种转换的尝试,但从来没有一种方法是 100% 完整且正确的。I don't believe Javascript includes any mechanism for doing this. There's a method
java.lang.Float.floatBitsToIntBits()
in Java, so depending on your intended environment you might be able to make use of that. If all else fails, you might have to send the data back to the server to be converted. Alternatively, I've seen attempts at Javascript methods to do this conversion, but never one that was 100% complete and correct.