Bitwise operations on 32-bit unsigned ints?

You only have to follow these rules:

  1. always end bit wise ops with >>> 0 so the result gets interpreted as unsigned.
  2. don't use >>. 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.


It's ugly, but:

var a = 1986735448;
var b = (a << 1) >>> 0;
/* b = 3973470896 */

JavaScript takes care of this problem by offering two bit shift operators, >> and >>>. You want >>> to do a shift without shifting the sign bit.