How to Convert a string into binary

H

HNT20

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
 
F

Felipe Almeida Lessa

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.
 
R

Rune Strand

HNT20 said:
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
"""
 
D

Duncan Booth

HNT20 said:
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.
return "01"[n%2]
return b1(n>>1)+b1(n)
return b2(n>>2)+b2(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)
'0110100001101001'
 
B

bearophileHUGS

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)
 
F

Fredrik Lundh

HNT20 said:
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>
 
H

HNT20

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.
 
H

HNT20

Rune said:
HNT20 said:
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
 
H

HNT20

Felipe said:
Em Sáb, 2006-04-15 às 19:25 +0000, HNT20 escreveu:

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
 
T

Terry Reedy

HNT20 said:
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
 
F

Felipe Almeida Lessa

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]
 
D

Dennis Lee Bieber

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.
For the (very rough) algorithm you give as an example, I'd probably
just use a mask&shift cycle...
.... ic = ord(c)
.... for i in range(8):
.... if ic & 1:
.... print 1,
.... else:
.... print -1,
.... ic = ic / 2 #NOTE: running LSB first
....
1 -1 -1 -1 -1 1 1 -1 -1 1 -1 -1 -1 1 1 -1 1 1 -1 -1 -1 -1 1 -1 -1 -1 1
-1 -1 -1 1 -1 -1 -1 -1 1 1 1 1 -1 1 -1 -1 1 1 -1 1 -1 -1 1 -1 1 1 1 1 -1
If you really want to build strings of 1 and 0 first... Convert to
hex, and use a lookup table...
.... "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" }.... x = "%X" % ord(c)
.... for n in x:
.... print table[n],
....
0110 0001 0110 0010 0100 0011 0100 0100 0111 1000 0101 1001 0111 1010

This runs in MSB order...
--
 
J

John Machin

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.
 
J

Jesse Hager

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.
 
G

Grant Edwards

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.
 
Joined
Oct 8, 2009
Messages
1
Reaction score
0
converting a string to binary

I don't know why this forum shows up in google as number 1, by now everyone should be using bin(). It's a built-in function of python that converts an integer to a binary. Usage: bin(ord(char))

import binascii
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top