Formula

Shamelessly, I copied it from Gray Code on Wikipedia.

Gray(N) = (n >> 1) XOR n

Tricky bit manipulation just change only 1 bit of n