Bin/dec representation – python

I’ve found these code snippets at ActiveStates code library. Quite useful if you need to convert between decimal and binary representation of integers:

def tobin(x, count=4):
    return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))

def todecimal(x):
    return sum(map(lambda z: int(x[z]) and 2**(len(x) - z - 1), range(len(x)-1, -1, -1)))

Comments are closed.

blog comments powered by Disqus