How to Convert a string into binary

HNT20 hnt20 at msn.com
Sat Apr 15 17:43:24 EDT 2006


bearophileHUGS at lycos.com wrote:
> If (assuming this is correct, you can do more tests) the given strings
> are many and/or long, this can be a fast version. With Psyco this same
> version can become quite faster.
> Bye,
> bearophile
> 
> 
> from array import array
> 
> class ToBinary(object):
>     """ToBinary: class to convert a given string to a binary string."""
>     def __init__(self):
>         _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"}
>         self._bytes = ["".join(_nibbles[h] for h in "%X"%i).zfill(8)
> for i in xrange(256)]
>     def conv(self, s):
>         if s:
>             result = [self._bytes[el] for el in array("B", s)]
>             result[0] = result[0].lstrip("0")
>             return "".join(result)
>         else:
>             return "0"
> 
> # Tests
> Conv2 = ToBinary()
> data = ["", "a", "b", "ab", "hello", "123456789"]
> for s in data:
>     print s, Conv2.conv(s)
> 

Thanks you very much, i will give this code a try. i hope it will work.



More information about the Python-list mailing list