convert a long string in binary
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Sun Aug 20 07:55:20 EDT 2006
bussiere maillist:
> i've got a very long string
> and i wanted to convert it in binary
Not much tested:
_nibbles = {"0":"0000", "1":"0001", "2":"0010", "3":"0011",
"4":"0100", "5":"0101", "6":"0110", "7":"0111",
"8":"1000", "9":"1001", "A":"1010", "B":"1011",
"C":"1100", "D":"1101", "E":"1110", "F":"1111"}
def toBase2(number):
if number < 16:
return "0000" + _nibbles["%X" % number]
else:
d1, d2 = "%X" % number
return _nibbles[d1] + _nibbles[d2]
convbin = dict((chr(i), toBase2(i)) for i in xrange(256))
def binary(s):
return "".join(convbin[c] for c in s)
print binary("testing string")
Surely there are ways to make it shorter (But it's fast enough).
Bye,
bearophile
More information about the Python-list
mailing list