# How to Convert a string into binary

Discussion in 'Python' started by HNT20, Apr 15, 2006.

1. ### HNT20Guest

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

HNT20, Apr 15, 2006

2. ### Felipe Almeida LessaGuest

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.

Felipe Almeida Lessa, Apr 15, 2006

3. ### Rune StrandGuest

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
"""

Rune Strand, Apr 15, 2006
4. ### Duncan BoothGuest

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'

Duncan Booth, Apr 15, 2006
5. ### Guest

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, 2006
6. ### Fredrik LundhGuest

"HNT20" <> 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>

Fredrik Lundh, Apr 15, 2006
7. ### HNT20Guest

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.

HNT20, Apr 15, 2006
8. ### HNT20Guest

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

HNT20, Apr 15, 2006
9. ### HNT20Guest

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

HNT20, Apr 15, 2006
10. ### Terry ReedyGuest

"HNT20" <> wrote in message
news:KMb0g.92182\$...
> 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

Terry Reedy, Apr 15, 2006
11. ### Felipe Almeida LessaGuest

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.

Felipe Almeida Lessa, Apr 16, 2006
12. ### Dennis Lee BieberGuest

On Sat, 15 Apr 2006 21:47:02 GMT, HNT20 <> declaimed the
following in comp.lang.python:

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

>>> data = "abCDxYz"
>>> for c in data:

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

>>> table = { "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" }
>>> for c in data:

.... 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...
--
> ============================================================== <
> | Wulfraed Dennis Lee Bieber KD6MOG <
> | Bestiaria Support Staff <
> ============================================================== <
> Overflow Page: <http://wlfraed.home.netcom.com/> <

Dennis Lee Bieber, Apr 16, 2006
13. ### John MachinGuest

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.

John Machin, Apr 16, 2006
14. ### Jesse HagerGuest

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 = "".decode("rot13")

Jesse Hager, Apr 16, 2006
15. ### Grant EdwardsGuest

On 2006-04-16, John Machin <> 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

--
Grant Edwards

Grant Edwards, Apr 16, 2006

Joined:
Oct 8, 2009
Messages:
1