Skip to content

Instantly share code, notes, and snippets.

@EmilHernvall
Created May 3, 2011 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmilHernvall/953796 to your computer and use it in GitHub Desktop.
Save EmilHernvall/953796 to your computer and use it in GitHub Desktop.
Some small python functions for converting between binary and denary
def Denary2Binary(n):
'''convert denary integer n to binary string bStr'''
bStr = ''
if n < 0: raise ValueError, "must be a positive integer"
if n == 0: return '0'
while n > 0:
bStr = str(n % 2) + bStr
n = n >> 1
return bStr
def int2bin(n, count=24):
"""returns the binary of integer n, using count number of digits"""
return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])
def bindecode(str): return "".join(map(lambda x: chr(int(x, 2)), str.split(" ")))
def binencode(str): return " ".join(map(lambda x: utils.int2bin(ord(x))[-8:], list(str)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment