translating ascii to binary
Canned
user at domain.invalid
Wed Sep 17 13:34:31 EDT 2008
Steven D'Aprano schreef:
> 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*
>
It's a bad habit, I can't help it. From now on, I'll follow your advice
to split the functionality into small, self-contained pieces. That
popping and inserting is just a workaround for another workaround.
> 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)
>
I've spend 3 days to find out what did I do wrong, but you did it in
just half an hour/more. You're my hero.
More information about the Python-list
mailing list