Skip to content

Instantly share code, notes, and snippets.

@4rzael
Last active August 11, 2017 16:29
Show Gist options
  • Save 4rzael/7b142302be0badda7dfac59e8b76aef9 to your computer and use it in GitHub Desktop.
Save 4rzael/7b142302be0badda7dfac59e8b76aef9 to your computer and use it in GitHub Desktop.
A simple Anti-Gray Code (And Gray Code too) generator in python 3.6+
#!/usr/bin/env python3
from functools import lru_cache
@lru_cache(maxsize=None)
def compute_gray_code(bits:int) -> list:
if bits is 1:
return [0, 1]
else:
smaller = compute_gray_code(bits - 1)
return smaller + [v | 2 ** (bits-1) for v in smaller][::-1]
@lru_cache(maxsize=None)
def compute_anti_gray_code(bits:int) -> list:
if (bits is 1):
return [0, 1]
max_int = (2 ** bits) - 1
res = compute_gray_code(bits - 1)
res = [value << 1 for value in res] # left shift
res = sum([[value, (~value) & max_int] for value in res], []) # duplicate and complements
return res
def anti_gray_code(value:int, bits:int) -> int:
return compute_anti_gray_code(bits)[value]
def gray_code(value:int, bits:int) -> int:
return compute_gray_code(bits)[value]
if __name__ == '__main__':
from sys import argv
from math import ceil
def main():
if len(argv) >= 3:
value = int(argv[1])
bits = int(argv[2])
if value >= 2 ** bits - 1 or value < 0:
print('Bad value or not enough bits')
return
res = anti_gray_code(value, bits)
print(res)
print(hex(res)[2:].zfill(ceil(bits / 4)).upper())
print(bin(res)[2:].zfill(bits))
else:
print('USAGE :', argv[0], 'VALUE BITS')
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment