convert a long string in binary

Maric Michaud maric at aristote.info
Tue Aug 22 06:08:37 EDT 2006


Le dimanche 20 août 2006 13:55, bearophileHUGS at lycos.com a écrit :
> 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).
>

Maybe this one is more elegant :

In [305]: trans = {}

In [306]: for i in range(256) :
   .....:     trans[chr(i)] = ''.join(i & 2**j and '1' or '0'
   .....:                             for j in reversed(range(8)))
   .....:

In [307]: trans['a']
Out[307]: '01100001'

In [308]: trans['\xee']
Out[308]: '11101110'

In [309]: print ''.join(trans[e] for e in 'test string')
0111010001100101011100110111010000100000011100110111010001110010011010010110111001100111


> Bye,
> bearophile

-- 
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097



More information about the Python-list mailing list