How to Convert a string into binary

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sat Apr 15 16:22:18 EDT 2006


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)




More information about the Python-list mailing list