473,228 Members | 1,646 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,228 software developers and data experts.

translating ascii to binary

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
Sep 17 '08 #1
5 2525
Lie
On Sep 17, 11:02*pm, Canned <u...@domain.invalidwrote:
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.
Sep 17 '08 #2
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>

Sep 17 '08 #3
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

Sep 17 '08 #4
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.
Sep 17 '08 #5
Lie
On Sep 17, 11:34*pm, Fredrik Lundh <fred...@pythonware.comwrote:
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.
Sep 25 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Bix | last post by:
As this is my very first post, I'd like to give thanks to all who support this with their help. Hopefully, this question hasn't been answered (too many times) before... If anyone could explain...
8
by: Bernhard Hidding | last post by:
Hi, my program writes chars to an ascii file via ofstream. You can use "\n" for newline and "\t" for tab there, but is there any command that deletes the last char in the current ofstream? Thanks...
22
by: Sunner Sun | last post by:
Hi, all Since the OS look both ASCII and binary file as a sequence of bytes, is there any way to determine the file type except to judge the extension? Thank you!
5
by: sathyashrayan | last post by:
Group, I have some doubts in the following program. ------------------program--------------------- /* ** Make an ascii binary string into an integer. */ #include <string.h> unsigned int...
13
by: greg | last post by:
Hello, I'm searching to know if a local file is ascii or binary. I couldn't find it in the manual, is there a way to know that ? thanks, -- greg
6
by: SandyMan | last post by:
Hi, I am able to open a binary file for reading but can someone tell me as how to go about converting a Binary file to ASCII file using C. Thanks In Advance SandyMan
68
by: vim | last post by:
hello everybody Plz tell the differance between binary file and ascii file............... Thanks in advance vim
6
by: as400tips | last post by:
I have a Binary Data file (Packed Decimal and ASCII mixed) and would like to convert into ASCII (readable) file. How to do it in C#? Thanks.
7
by: azrael | last post by:
Hy folks, I googled, and searched, and can not bealive that I have not found a built in way to convert the easy and elegant python way a function to easily convert simple ascii data to binary...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.