Converting an integer to base 2
Skip Montanaro
skip at pobox.com
Fri Nov 30 14:12:32 EST 2001
Stephen> I'm trying to convert integers to base 2. Can someone tell me
Stephen> why this doesn't work?
>>> int('5', 2)
Traceback (most recent call last):
File "<pyshell#102>", line 1, in ?
int('5', 2)
ValueError: invalid literal for int(): 5
int(s, n) means interpret s as a number in base n. '5' is not a valid
binary literal, hence the exception. This works:
>>> int("101", 2)
5
but is probably not what you want. I expect you really want to go the other
way: return the string that represents the number 5 in base 2. There is no
"%b" format string in Python's string interpolation, but you can whip
something up easily:
map16 = {"f": "1111", "e": "1110", "d": "1101", "c": "1100",
"b": "1011", "a": "1010", "9": "1001", "8": "1000",
"7": "0111", "6": "0110", "5": "0101", "4": "0100",
"3": "0011", "2": "0010", "1": "0001", "0": "0000",
}
def binary(n):
return "".join([map16[c.lower()] for c in "%x" % n])
if __name__ == "__main__":
for n in [0, 1, 27, 93, 1024, 55]:
print n, "->", binary(n)
(This isn't original with me. I saw something similar on the list a few
months ago.)
--
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)
More information about the Python-list
mailing list