translating ascii to binary

Discussion in 'Python' started by Canned, Sep 17, 2008.

  1. Canned

    Canned Guest

    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
    > def ascii_to_bin(char):
    > ascii = ord(char)
    > bin = []
    >
    > while (ascii > 0):
    > if (ascii & 1) == 1:
    > bin.append("1")
    > else:
    > bin.append("0")
    > ascii = ascii >> 1
    >
    > bin.reverse()
    > binary = "".join(bin)
    > zerofix = (8 - len(binary)) * '0'
    >
    > return zerofix + binary
    >
    >
    >
    > some_string = 'Time to go now, Rummy?'
    >
    > binary = []
    > for char in some_string:
    > binary.append(ascii_to_bin(char))
    >
    > print binary
    > print " ".join(binary)


    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.

    > if len(sys.argv) < 2:
    > print 'usage:', os.path.basename(sys.argv[0]), 'text'
    > sys.exit()
    >
    > class Converterab:
    > '''
    > Ascii-binary converter.
    > '''
    > def __init__(self, string):
    > self.string = string
    >
    > def ascii_to_bin(self):
    > bindump = []
    > for char in self.string:
    > bin = ord(char)
    > while bin > 0:
    > if (bin & 1) == 1:
    > bindump.append("1")
    > else:
    > bindump.append("0")
    > bin = bin >> 1
    > bindump.reverse()
    > print bindump # Debug tool, delete this
    >
    > '''
    > Zero fix in bindump
    > '''
    > bindump.insert(0, "0")
    > count = 0
    > pos = 0
    > for dg in bindump:
    > count += 1
    > pos += 1
    > if count == 8:
    > bindump.insert(pos, "0")
    > count = 0
    > bindump.pop()
    > print bindump # Debug tool, delete this, the best result so far
    >
    > '''
    > Reversing array per byte
    > '''
    > final = []
    > pos -= pos # Set pos to 0 again
    > while len(bindump) != 0:
    > print count # Debug tool, delete this, this is weird, start at 1, I expected 0
    > count += 1
    > if count > 8:
    > pos += 8
    > count -= count
    > final.insert(pos, bindump.pop())
    > print final # Debug tool, delete this
    > '''
    > for ar in bindump:
    > count += 1
    > if (count < 8):
    > final.insert(pos, bindump.pop())
    > elif (count >= 8):
    > pos = count
    > final.insert(pos, bindump.pop())
    > else:
    > final.insert(pos, bindump.pop())
    > '''
    > final.insert(0, final.pop())
    >
    > binary = "".join(final)
    > return binary
    >
    > result = Converterab(sys.argv[1])
    >
    > print "Char : ", result.ascii_to_bin()


    The problem start at "Reversing array per byte". That block should
    reversing the array from 'bindump' and copy it to 'final' per 8 items,
    e.g. a = ['0', '1', '0', '1', '0', '1', '0', '1', '2', '1', '2', '1',
    '2', '1', '2', '1', '3', '2', '3', '2', '3', '2', '3', '2']
    b = ['3', '2', '3', '2', '3', '2', '3', '2', '2', '1', '2', '1', '2',
    '1', '2', '1', '0', '1', '0', '1', '0', '1', '0', '1']

    Any advice about this matter would be very appreciated.
    Thanks in advance.

    C
     
    Canned, Sep 17, 2008
    #1
    1. Advertising

  2. Canned

    Lie Guest

    On Sep 17, 11:02 pm, 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
    >
    >
    >
    >
    >
    > > def ascii_to_bin(char):
    > > ascii = ord(char)
    > > bin = []

    >
    > > while (ascii > 0):
    > > if (ascii & 1) == 1:
    > > bin.append("1")
    > > else:
    > > bin.append("0")
    > > ascii = ascii >> 1

    >
    > > bin.reverse()
    > > binary = "".join(bin)
    > > zerofix = (8 - len(binary)) * '0'

    >
    > > return zerofix + binary

    >
    > > some_string = 'Time to go now, Rummy?'

    >
    > > binary = []
    > > for char in some_string:
    > > binary.append(ascii_to_bin(char))

    >
    > > print binary
    > > print " ".join(binary)

    >
    > 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.
    >
    >
    >
    >
    >
    > > if len(sys.argv) < 2:
    > >         print 'usage:', os.path.basename(sys.argv[0]), 'text'
    > >         sys.exit()

    >
    > > class Converterab:
    > >         '''
    > >         Ascii-binary converter.
    > >         '''
    > >         def __init__(self, string):
    > >                 self.string = string

    >
    > >         def ascii_to_bin(self):
    > >                 bindump = []
    > >                 for char in self.string:
    > >                         bin = ord(char)
    > >                         while bin > 0:
    > >                                 if (bin & 1) == 1:
    > >                                         bindump.append("1")
    > >                                 else:
    > >                                         bindump.append("0")
    > >                                 bin = bin >> 1
    > >                 bindump.reverse()
    > >                 print bindump   # Debug tool, delete this

    >
    > >                 '''
    > >                 Zero fix in bindump
    > >                 '''
    > >                 bindump.insert(0, "0")
    > >                 count = 0
    > >                 pos = 0
    > >                 for dg in bindump:
    > >                         count += 1
    > >                         pos += 1
    > >                         if count == 8:
    > >                                 bindump..insert(pos, "0")
    > >                                 count = 0
    > >                 bindump.pop()
    > >                 print bindump   # Debug tool, delete this, the best result so far

    >
    > >                 '''
    > >                 Reversing array per byte
    > >                 '''
    > >                 final = []
    > >                 pos -= pos      # Set pos to 0 again
    > >                 while len(bindump) != 0:
    > >                         print count     # Debug tool, delete this, this is weird, start at 1, I expected 0
    > >                         count += 1
    > >                         if count > 8:
    > >                                 pos += 8
    > >                                 count -= count
    > >                         final.insert(pos, bindump.pop())
    > >                         print final     # Debug tool, delete this
    > >                 '''
    > >                 for ar in bindump:
    > >                         count += 1
    > >                         if (count < 8):
    > >                                 final.insert(pos, bindump.pop())
    > >                         elif (count >= 8):
    > >                                 pos = count
    > >                                 final.insert(pos, bindump.pop())
    > >                         else:
    > >                                 final.insert(pos, bindump.pop())
    > >                 '''
    > >                 final.insert(0, final.pop())

    >
    > >                 binary = "".join(final)
    > >                 return binary

    >
    > > result = Converterab(sys.argv[1])

    >
    > > print "Char : ", result.ascii_to_bin()

    >
    > The problem start at "Reversing array per byte". That block should
    > reversing the array from 'bindump' and copy it to 'final' per 8 items,
    > e.g. a = ['0', '1', '0', '1', '0', '1', '0', '1', '2', '1', '2', '1',
    > '2', '1', '2', '1', '3', '2', '3', '2', '3', '2', '3', '2']
    > b = ['3', '2', '3', '2', '3', '2', '3', '2', '2', '1', '2', '1', '2',
    > '1', '2', '1', '0', '1', '0', '1', '0', '1', '0', '1']
    >
    > Any advice about this matter would be very appreciated.
    > Thanks in advance.


    It'd be easier to make a one-char version of ascii2bin then make the
    string version based on the one-char version.
     
    Lie, Sep 17, 2008
    #2
    1. Advertising

  3. Lie wrote:

    >> Any advice about this matter would be very appreciated.
    >> Thanks in advance.

    >
    > It'd be easier to make a one-char version of ascii2bin then make the
    > string version based on the one-char version.


    And it'd be a lot easier to read your posts if you trimmed away at least
    some of the original message before posting. If you cannot do that for
    some technical reason, I recommend using top-posting instead.

    </F>
     
    Fredrik Lundh, Sep 17, 2008
    #3
  4. 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
     
    Steven D'Aprano, Sep 17, 2008
    #4
  5. Canned

    Canned Guest

    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.
     
    Canned, Sep 17, 2008
    #5
  6. Canned

    Lie Guest

    On Sep 17, 11:34 pm, Fredrik Lundh <> wrote:
    > Lie wrote:
    > >> Any advice about this matter would be very appreciated.
    > >> Thanks in advance.

    >
    > > It'd be easier to make a one-char version of ascii2bin then make the
    > > string version based on the one-char version.

    >
    > And it'd be a lot easier to read your posts if you trimmed away at least
    > some of the original message before posting.  If you cannot do that for
    > some technical reason, I recommend using top-posting instead.
    >
    > </F>



    Ah.. yes, sorry for that, I had never thought about that since I use
    Google Groups, which automatically trim long quotes, to access the
    list.
     
    Lie, Sep 25, 2008
    #6
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Marc Schellens
    Replies:
    8
    Views:
    3,054
    John Harrison
    Jul 15, 2003
  2. TOXiC
    Replies:
    5
    Views:
    1,311
    TOXiC
    Jan 31, 2007
  3. James O'Brien
    Replies:
    3
    Views:
    287
    Ben Morrow
    Mar 5, 2004
  4. Alextophi
    Replies:
    8
    Views:
    568
    Alan J. Flavell
    Dec 30, 2005
  5. bruce
    Replies:
    38
    Views:
    313
    Mark Lawrence
    Nov 1, 2013
Loading...

Share This Page