Bitwise operator magic:

Here are some magic of bitwise operator:

a) x & (x -1) : equals to x with least significant bit cleared.
for example:
x = 10001100 then,
x & (x-1) =  10001000

b) x & !(x-1) :  extracts the lowest set bit of x and all other bits are cleared.
for example:
x = 10001100 then,
x & !(x-1) =  00000100

c) x XOR (x >> 1) : standard gray code (i.e. binary reflected) of x.

You can get more about this from here.
Here you will get a lot stuffs on bitwise operator like:

  • Detect if two integers have opposite signs
  • Compute the integer absolute value (abs) without branching
  •  Compute the minimum (min) or maximum (max) of two integers without branching
  •  Determining if an integer is a power of 2
  •  Conditionally set or clear bits without branching
  •  Counting bits set (naive way) etc.
Author: Hrishikesh Mishra