为什么 100 >> 100 和 100 >>> 100 return 6 in Javascript?
Why does 100 >> 100 and 100 >>> 100 return 6 in Javascript?
The right shift operator (>>) shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".
据我了解,由于 100 是 0b1100100
,因此向右移动 100 次应该得到 0b0
。但是,当我在运行100 >> 100
中Javascript(使用chrome)时,它returns 6.为什么会这样?我猜这与 JS 对数字的内部表示有关,但想更清楚地了解。
编辑:即使使用无符号 >>>
运算符,答案仍然是 6。 Sign/unsigned 好像没关系。
无符号运算documentation:
The unsigned right shift operator (>>>) (zero-fill right shift) shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always non-negative. Unlike the other bitwise operators, zero-fill right shift returns an unsigned 32-bit integer.
取右边的值mod32。(即只使用最后五位。)如果你计算100>>32
,你会得到100
,这是计算 100>>0
时得到的结果相同。之后,100>>33
就是50
,如此循环往复
The right shift operator (>>) shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".
据我了解,由于 100 是 0b1100100
,因此向右移动 100 次应该得到 0b0
。但是,当我在运行100 >> 100
中Javascript(使用chrome)时,它returns 6.为什么会这样?我猜这与 JS 对数字的内部表示有关,但想更清楚地了解。
编辑:即使使用无符号 >>>
运算符,答案仍然是 6。 Sign/unsigned 好像没关系。
无符号运算documentation:
The unsigned right shift operator (>>>) (zero-fill right shift) shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always non-negative. Unlike the other bitwise operators, zero-fill right shift returns an unsigned 32-bit integer.
取右边的值mod32。(即只使用最后五位。)如果你计算100>>32
,你会得到100
,这是计算 100>>0
时得到的结果相同。之后,100>>33
就是50
,如此循环往复