Created
May 3, 2011 17:39
-
-
Save EmilHernvall/953796 to your computer and use it in GitHub Desktop.
Some small python functions for converting between binary and denary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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