473,405 Members | 2,354 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,405 software developers and data experts.

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 22064
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: David Lawson | last post by:
I know how to conver a string to an array of strings, but I need to convert an ascii string to an array of integers (really unsigned chars). Eg, $str ="ABC"; needs to convert to something...
4
by: CSharpener | last post by:
This should be *so* easy! How do I convert a Byte or int to a binary string representation in C# In JavaScript, it goes like this for an int: javascript:(123).toString(2 or...
8
by: John A Grandy | last post by:
could someone please discuss the pros and cons of CType(MyDouble,Decimal) versus Convert.ToDecimal(MyDouble) .... and other such conversions ...
25
by: Charles Law | last post by:
I thought this was going to be straight forward, given the wealth of conversion functions in .NET, but it is proving more convoluted than imagined. Given the following <code> Dim ba(1) As...
6
by: MrKrich | last post by:
I want to convert Hexadecimal or normal integer to Binary. Does VB.Net has function to do that? I only found Hex function that convert normal integer to Hexadecimal.
4
by: Russell Warren | last post by:
I've got a case where I want to convert binary blocks of data (various ctypes objects) to base64 strings. The conversion calls in the base64 module expect strings as input, so right now I'm...
3
by: bussiere maillist | last post by:
i've got a very long string and i wanted to convert it in binary like string = """Monty Python, or The Pythons, is the collective name of the creators of Monty Python's Flying Circus, a British...
7
by: elliotng.ee | last post by:
I have a text file that contains a header 32-bit binary. For example, the text file could be: %%This is the input text %%test.txt Date: Tue Dec 26 14:03:35 2006...
5
by: =?Utf-8?B?YmJkb2J1ZGR5?= | last post by:
I am having a problem converting string to binary and I am hoping someone can help me out I have a sql query that does an update that updates a binary field calles password ...
6
by: Bob Altman | last post by:
Hi all, I'm looking for the fastest way to convert an array of bytes to String. I also need to convert a String back to its original Byte() representation. Convert.ToBase64String and...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.