translating ascii to binary

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Sep 17 12:49:24 EDT 2008


On Wed, 17 Sep 2008 18:02:15 +0200, Canned wrote:

> Hi,
> I'm trying to write a class that can convert ascii to binary and vice
> versa. I write my class based on this function I've found on internet

[...]

> That works perfectly, but when I try to implement it in my own class it
> gives me alot of headache, also because I'm totally new to the language.
> It work only with one character at a time, and if I give a string it
> just give some weird result.


[snip code]

Your "ascii_to_bin" method tries to do too much in one method. You should 
split the functionality into small, self-contained pieces, then combine 
them. And frankly, once you got to the part where you started popping and 
inserting, my brain melted. You are making an easy job too hard! *smiles*

Try this instead:

class Converterab:
    '''
    Ascii-binary converter.
    '''
    def __init__(self, string):
        self.string = string
    def bin(self, n):
        """Return the binary representation of a positive integer n."""
        bindump = []
        while n > 0:
            bindump.append(str(n & 1))
            n = n >> 1
        bindump.reverse()
        if bindump:
            return ''.join(bindump)
        else:
            return '0'
    def char_to_bin(self, c):
        """Return the binary representation of a character c."""
        bits = self.bin(ord(c))
        zeroes = "0" * (8-len(bits))
        return zeroes+bits
    def ascii_to_bin(self):
        results = []
        for c in self.string:
            results.append(self.char_to_bin(c))
        return ''.join(results)



-- 
Steven




More information about the Python-list mailing list