在Javascript中以负移位计数向左移位 [英] Left shifting with a negative shift count in Javascript

查看:52
本文介绍了在Javascript中以负移位计数向左移位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Javascript中注意到的一件事-

A thing which I noticed in Javascript -

a<<-1

a << -1

Returns 0 when a = even.
Returns -2147483648 when a = odd.

类似地,当 -1 更改为其他 -ve 数字时,将返回不同的值.有人能解释一下幕后进行的是什么操作吗?还是行为未定义?

Similarly, different values are returned when -1 is changed to some other -ve number. Can someone explain what bit operations are taking place under the hood ? Or is the behavior undefined ?

谢谢

编辑

也不应零填充右移,即 -2>>>1 返回 7 吗?

Also shouldn't Zero-fill right shift i.e. -2 >>> 1 return 7 ?

-2 =1110.之后,以零填充向右移位,它应为0111 = 7

-2 = 1110. After, right shift with zero-fill, it should give 0111 = 7

但是 a = -2;console.log(a>>> 1); 退货 2147483647

推荐答案

我也对此很疑惑,这就是我登陆这里的方式.我做了一些研究,并弄清了行为.本质上, JavaScript 将操作数和移位值视为位序列,而不是数字.它与32位整数(浮点数被截断)一起使用,最大移位为32位.如果我们移位大于32的数字,则所有位都将移出,结果为零.为了确保偏移量小于或等于32,JavaScript会截断5个最低有效位[ a< <;(b& 0x1F)]或使用模数方法[ a<<(b%32)]产生相同的结果.

I too wondered about this which is how I landed here. I’ve done a little research and figured out the behavior. Essentially JavaScript treats the operand and shift value as sequences of bits rather than as numbers. It works with 32 bit integers (floats get truncated) and the maximum shift is 32 bits. If we shift by a number greater than 32, all the bits would shift out, resulting in zero. To ensure the shift is less than or equal to 32, JavaScript truncates the 5 least significant bits [a << (b&0x1F)] or possibly with the modulus method [a << (b%32)] which yields the same result.

通过这种方式,将要转移的负数视为一个位序列,而不是一个负数(即-1).在这种情况下, b = -1 = 0xFFFFFFFF .由于此数字大于32,因此将其截断为 0xFFFFFFFF&0x1F = 31 0xFFFFFFFF%32 = 31 .

With that out of the way, think of the negative number you are shifting by as a sequence of bits, not a negative number (i.e. -1). In this case b = -1 = 0xFFFFFFFF. Since this number is larger than 32, it is truncated 0xFFFFFFFF & 0x1F = 31 or 0xFFFFFFFF % 32 = 31.

因此,在您的示例中,"a"从最低有效位一直移到最高有效位(符号位).因此,移位的结果为 0x00000000 或( 0x80000000 = -2147483648 ),具体取决于操作数是否设置了1位(奇数或偶数).

So in your example "a" gets shifted all the way from the least significant bit to the most significant bit (the sign bit). Therefor the result of the shift is either 0x00000000 or (0x80000000 = -2147483648) depending on whether the operand had the 1 bit set (odd or even).

这篇关于在Javascript中以负移位计数向左移位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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