如何从32位方式操作产生的JavaScript代码的数字转换回64位数字 [英] How are 32 bit JavaScript numbers resulting from a bit-wise operation converted back to 64 bit numbers

查看:722
本文介绍了如何从32位方式操作产生的JavaScript代码的数字转换回64位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解如何在JavaScript中工作位操作,更具体怎么从位操作所产生的32位数字转换回一个64位的JavaScript号。在一个32位的数字设置最左边位时,当操作溢出我收到一些奇怪的结果。

例如,具有以下操作:

  0×01<< 31

通常会导致为0x80000000 如果数量为32位长。但是JavaScript时这个数字转换回一个64位的值,它padds与 1 最左边的32位导致的价值 FFFFFFFF80000000

同样,左移32位,从而溢出一个32位整数,与该操作时:

  0X02<< 32

数量将溢出,结果值应 0×00 。但由此产生的JavaScript的数量是 0×02

有没有什么具体的规则,使用的JavaScript为我不知道的位操作?据我所知,所有的逐位运算的执行与32位整数,而JavaScript的数字是64位双precision浮点数字,但我不明白的地方的微胖来自于两者之间转换时。


解决方案

  1. 位运算符的结果是签署的INT32的,当它们被转换回数字符号位被传播。


  2. 您不能超过31位转移:


让shiftCount转换为掩蔽掉所有但RNUM的至少显著5比特的结果,也就是计算RNUM&安培;为0x1F。

这就是 X<< 32 相同 X<< 0

I am trying to understand how bit-wise operation in JavaScript work, more specifically how the 32 bit number resulting from a bit-wise operation is converted back to a 64 bit JavaScript number. I am getting some strange results when setting the left most bit in a 32 bit number and when the operation overflows.

For example, with the following operation:

0x01 << 31

Would normally result in 0x80000000 if the number was 32 bits long. But when JavaScript converts this number back to a 64 bit value, it padds the leftmost 32 bits with 1 resulting in the value FFFFFFFF80000000.

Similarly, when left shifting 32 bits, thus overflowing a 32 bit integer, with the operation:

0x02 << 32

The number would overflow, and the result value should be 0x00. But the resulting JavaScript number is 0x02.

Are there any specific rules that JavaScript uses for bit-wise operation that I am not aware of? I understand that all bit-wise operations are performed with 32 bit integers, and that JavaScript numbers are 64 bit double precision floating point numbers, but I cannot understand where the extra padding comes from when converting between the two.

解决方案

  1. Result of bitwise operators are signed int32's, the sign bit is propagated when they are converted back to Numbers.

  2. You cannot shift by more than 31 bits:

Let shiftCount be the result of masking out all but the least significant 5 bits of rnum, that is, compute rnum & 0x1F.

That is, x<<32 is the same as x<<0.

这篇关于如何从32位方式操作产生的JavaScript代码的数字转换回64位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆