Bit Manipulation Gray Code Sequence (Python)

Generate a Gray code sequence of n bits using bit manipulation where consecutive values differ by one bit.

PythonData Integrity

Code

snippet
def gray_code(n):
    count = 1 << n
    return [i ^ (i >> 1) for i in range(count)]


def gray_to_binary(gray):
    b = gray
    while gray >> 1:
        gray >>= 1
        b ^= gray
    return b


def popcount(x):
    x = x - ((x >> 1) & 0x55555555)
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
    x = (x + (x >> 4)) & 0x0F0F0F0F
    return (x * 0x01010101) >> 24