Bit Manipulation Gray Code Sequence (Python)
Generate a Gray code sequence of n bits using bit manipulation where consecutive values differ by one bit.
Code
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) >> 24How it works
Count the functions gray_code, gray_to_binary and popcount as the entire surface area of Bit Manipulation Gray Code Sequence (Python).
Repetition is confined to while gray >> 1 — the rest of the file is straight-line.
What comes back is a new object, not a reference to anything passed in.
Applying it
The main signature reads def gray_code(n)
gray_code is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
def gray_to_binary(gray):
b = gray
while gray >> 1:
gray >>= 1
b ^= gray
return b
def gray_code(n):
count = 1 << n
return [i ^ (i >> 1) for i in range(count)]
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0F0F0F0F
return (x * 0x01010101) >> 24
Interactive Tools for This Topic
FAQ
- Does `gray_code` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `gray_code`, `gray_to_binary`, `popcount` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.