469,273 Members | 1,794 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,273 developers. It's quick & easy.

How to Convert a string into binary

Hello All

i am new to python language. i am working on a gnuradio project where it
uses python as the primary programming language. i am trying to convert
a message, text, or numbers into binary code so that i can process it.

i googled many times and tried many of the answers out there, no luck so
far.

is there a way to convert a string into its binary representation of the
ascii table.??

an example of what i want would be:

hi --> 0110100001101001
Thanks
-HNT
Apr 15 '06 #1
13 21610
Em Sáb, 2006-04-15 *s 19:25 +0000, HNT20 escreveu:
is there a way to convert a string into its binary representation of the
ascii table.??


I'm very curious... why?

And no, I don't have the answer.

--
Felipe.

Apr 15 '06 #2

HNT20 wrote:
Hello All


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)

some_string = 'Time to go now, Rummy?'

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

print binary
print " ".join(binary)

"""
['01010100', '01101001', '01101101', '01100101', '00100000',
'01110100', '01101111', '00100000', '01100111', '01101111', '00100000',
'01101110', '01101111', '01110111', '00101100', '00100000', '01010010',
'01110101', '01101101', '01101101', '01111001', '00111111']
01010100 01101001 01101101 01100101 00100000 01110100 01101111 00100000
01100111 01101111 00100000 01101110 01101111 01110111 00101100 00100000
01010010 01110101 01101101 01101101 01111001 00111111
"""

Apr 15 '06 #3
HNT20 wrote:
is there a way to convert a string into its binary representation of the
ascii table.??

an example of what i want would be:

hi --> 0110100001101001


Why not just write some code to do it? e.g.
def b1(n): return "01"[n%2]
def b2(n): return b1(n>>1)+b1(n)
def b3(n): return b2(n>>2)+b2(n)
def b4(n): return b3(n>>4)+b3(n)
bytes = [ b4(n) for n in range(256)]
def binstring(s): return ''.join(bytes[ord(c)] for c in s)
binstring('hi')

'0110100001101001'
Apr 15 '06 #4
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)

Apr 15 '06 #5
"HNT20" <hn***@msn.com> wrote:
i am new to python language. i am working on a gnuradio project where it
uses python as the primary programming language. i am trying to convert
a message, text, or numbers into binary code so that i can process it.


umm. characters and numbers are stored in binary code, inside your com-
puter. what exactly makes you think you have to convert them to binary
strings in order to process them ?

</F>

Apr 15 '06 #6
be************@lycos.com wrote:
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)


Thanks you very much, i will give this code a try. i hope it will work.
Apr 15 '06 #7
Rune Strand wrote:
HNT20 wrote:
Hello All


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)

some_string = 'Time to go now, Rummy?'

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

print binary
print " ".join(binary)

"""
['01010100', '01101001', '01101101', '01100101', '00100000',
'01110100', '01101111', '00100000', '01100111', '01101111', '00100000',
'01101110', '01101111', '01110111', '00101100', '00100000', '01010010',
'01110101', '01101101', '01101101', '01111001', '00111111']
01010100 01101001 01101101 01100101 00100000 01110100 01101111 00100000
01100111 01101111 00100000 01101110 01101111 01110111 00101100 00100000
01010010 01110101 01101101 01101101 01111001 00111111
"""

Thanks very much. this code looks really promising. i will try to
implement this code and see if i get any luck

HNT
Apr 15 '06 #8
Felipe Almeida Lessa wrote:
Em Sáb, 2006-04-15 *s 19:25 +0000, HNT20 escreveu:
is there a way to convert a string into its binary representation of the
ascii table.??


I'm very curious... why?

And no, I don't have the answer.


well, once i get the binary representations, i can group the data and
modulate it to a higher frequency and transmit it for example, if i am
using BPSK modulation, i will then convert each zero into -1 and
multiply it with the sin function with the sampling frequency with a
hamming window. and so forth. yet, the first step is to have a
successful representation of the data.

HNT
Apr 15 '06 #9

"HNT20" <hn***@msn.com> wrote in message
news:KM*******************@tornado.ohiordc.rr.com. ..
i am new to python language. i am working on a gnuradio project where it
uses python as the primary programming language. i am trying to convert
a message, text, or numbers into binary code so that i can process it. ..... hi --> 0110100001101001


I would start by making a lookup table to translate the ordinals of ascii
chars to binary strings:
a2b = ['00000000', '00000001', '00000010', etc ...
using something that generates the binary strings (such as that posted).
If you don't want any or all of the initial 32 control chars translated,
replace the corresponding string with ''.

Then your main program is very simple:

# given string s
binchars = []
for c in s: binchars.append(a2b[ord(c)])

#if you really then need one long string instead of the list of strings
longstring = ''.join(binchars)
#or use any other connector than '', such as ' '.

Terry Jan Reedy


Apr 15 '06 #10
Em Sáb, 2006-04-15 *s 18:09 -0400, Terry Reedy escreveu:
# given string s
binchars = []
for c in s: binchars.append(a2b[ord(c)])


Faster:

binchars = [a2b[ord(c)] for c in s]

--
Felipe.

Apr 15 '06 #11
On 16/04/2006 5:25 AM, HNT20 wrote:

hi --> 0110100001101001


This implies that the bits in a byte are transmitted MSB first. I
haven't done anything anywhere near this area since about the time that
acoustic couplers went the way of buggy whips, but my vague recollection
is LSB first.

Apr 16 '06 #12
The short version:

def str2bin(s):
return ''.join([''.join(['10'[not (m&ord(x))] for m in
(128,64,32,16,8,4,2,1)]) for x in s])

Notes:

Split into 3 lines for newsgroup post, 3rd line is actually the end of
the 2nd. It will run as shown above.

Returns digits in MSB order, to return LSB first, reverse the order of
the bit weights. (1,2,4,8,16,32,64,128)

To support 16-bit Unicode, add powers of two to the bit weights up to 32768.

To put a separator between digits for each character put it between
first set of empty quote chars. ',' -> '00000000,11111111'

To put a separator between digits of the same character, put it between
the second set of empty quotes. '.' -> '0.1.0.1.0.1.0.1'

This is probably slower than one based on lookup tables like the others
are proposing.

--
Jesse Hager
email = "wr********@tznvy.pbz".decode("rot13")
Apr 16 '06 #13
On 2006-04-16, John Machin <sj******@lexicon.net> wrote:
On 16/04/2006 5:25 AM, HNT20 wrote:

hi --> 0110100001101001


This implies that the bits in a byte are transmitted MSB first. I
haven't done anything anywhere near this area since about the time that
acoustic couplers went the way of buggy whips, but my vague recollection
is LSB first.


It depends. "Normal" UARTs send LSB first. Some other types of
serial links are MSB first.

--
Grant Edwards
gr****@visi.com
Apr 16 '06 #14

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by David Lawson | last post: by
8 posts views Thread by John A Grandy | last post: by
3 posts views Thread by bussiere maillist | last post: by
7 posts views Thread by elliotng.ee | last post: by
5 posts views Thread by =?Utf-8?B?YmJkb2J1ZGR5?= | last post: by
6 posts views Thread by Bob Altman | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.