Introduction

Bitwise operators treat numbers as signed 32-bit integers. If you are not familiar with them, read the general stuff from wikipedia Bitwise Operation article. They are rarely used in most cases.

Following bitwise operators are supported:

  • AND ( & )
  • OR ( | )
  • XOR ( ^ )
  • NOT ( ~ )
  • LEFT SHIFT ( << )
  • RIGHT SHIFT ( >> )
  • ZERO-FILL RIGHT SHIFT ( >>> )

Unlike C language, bitwise operations are not very fast in JavaScript: So they shouldn’t be used low-level optimizations. Most of them are rarely used. Especially, the exotic zero-fill right shift.

Smart integer operations

There are several tricks with bitwise operations to make the code shorter and faster.

That’s because a single bitwise operation can give the same result as several ordinary numerical operations.

Smart -(n+1)

The notable exception is bitwise NOT (~).

Bitwise NOT on an integer n is same as -(n+1).

That is a side effect of inversing every bit of a number.

For example:

alert( ~1 )  // -2
alert( ~-1 ) // 0

Smart rounding

Another use of binary operators is rounding. Because they treat numbers as integers, all of them cut off the decimal part.

For example, double bitwise NOT doesn’t change the integer, but cuts off the decimal part:

alert( ~~12.34 ) // 12

Other bitwise operators can be used to do the same:

alert( 12.9 ^ 0 )  // 12
alert( -13.5 << 0 ) // 13

Smart division by power of 2

Regular division by 2 may return a floating point number. But binary operation always returns integer.

The right shift a >> b operator is actually same as a/2b.

See examples:

alert( 5 >> 1 ) // integer division without a remainder: 5 / 2 = 2
alert( 21 >> 2 ) // 21 / 4 = 5
alert( 21 >> 3 ) // 21 / 8 = 2
alert( 21 >> 4 ) // 21 / 16 = 1