JavaScript converts operands to 32-bit signed ints before doing bitwise operations. It also does the operation with 32-bit signed ints, meaning that the result is a 32-bit s
It's ugly, but:
var a = 1986735448;
var b = (a << 1) >>> 0;
/* b = 3973470896 */
You only have to follow these rules:
>>> 0
so the result gets interpreted as unsigned.>>
. If the left-most bit is 1 it will try to preseve the sign and thus will introduce 1
's to the left. Always use >>>
.Examples:
C: (3774191835 >> 2) | 2147483648
js: (3774191835 >>> 2 | 2147483648) >>> 0
C: 1986735448 << 1
js: (1986735448 << 1) >>> 0
C: 3774191835 & 4294967295
js: (3774191835 & 4294967295) >>> 0
Only if the last op is >>>
, >>> 0
is not necessary.
JavaScript takes care of this problem by offering two bit shift operators, >>
and >>>
. You want >>>
to do a shift without shifting the sign bit.