mesa177, I couldn't come up with anything geeky enough for your bday, so I decided to implement your algorithm (your "trick" really. It reminded me of this trick we were taught to convert bin to hex...) in Python.
For what it's worth, it shows how expressive Python's syntax is. Reading it will feel like pseudo-code describing the simplest approach :)
The thing I enjoy most about this code is the
implementation of XOR in function graypos.
def binpos (decnum, position):
if (decnum % 2**position) >= (2**(position-1)):
return 1
else:
return 0
def graypos (decnum, position):
''' return binpos(a) XOR binpos(a+1)
'''
if binpos(decnum, position) != binpos(decnum, position+1):
return 1
else:
return 0
def graysize (decnum):
i=0
while decnum >= 2**i:
i += 1
return i
def gray (decnum):
if decnum == 0:
return "0"
gray_list = []
for idx in range(graysize(decnum)):
gray_list.append(str(graypos(decnum, idx+1)))
gray_list.reverse()
return "".join(gray_list)
You can test it like this:
>>> for i in range(10):
print gray(i)
0
1
11
10
110
111
101
100
1100
1101