473,666 Members | 2,044 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 --> 011010000110100 1
Thanks
-HNT
Apr 15 '06 #1
13 22089
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(ch ar):
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(a scii_to_bin(cha r))

print binary
print " ".join(bina ry)

some_string = 'Time to go now, Rummy?'

binary = []
for char in some_string:
binary.append(a scii_to_bin(cha r))

print binary
print " ".join(bina ry)

"""
['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 --> 011010000110100 1


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

'01101000011010 01'
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(_nibble s[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(res ult)
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.co m> 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(_nibble s[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(res ult)
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(ch ar):
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(a scii_to_bin(cha r))

print binary
print " ".join(bina ry)

some_string = 'Time to go now, Rummy?'

binary = []
for char in some_string:
binary.append(a scii_to_bin(cha r))

print binary
print " ".join(bina ry)

"""
['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.co m> wrote in message
news:KM******** ***********@tor nado.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 --> 011010000110100 1


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(binchar s)
#or use any other connector than '', such as ' '.

Terry Jan Reedy


Apr 15 '06 #10

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

Similar topics

4
6099
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 like this: $buf = array(0x41, 0x42, 0x43); Anyone know how? I haven't been able to find a way.
4
4293
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 javascript:(0xFE).toString(2 No problem. So, how do I do the same in C#? What simple thing am I missing
8
7352
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
7262
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 Byte Dim b As Byte
6
43641
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
5530
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 converting the binary blocks to strings first, then converting the resulting string to base64. This seems highly inefficient and I'd like to just go straight from binary to a base64 string. Here is the conversion we're using from object to...
3
3124
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 television comedy sketch show that first aired on the BBC on October 5, 1969. A total of 45 episodes were made over four series. However, the Python phenomenon was much greater, spawning stage tours, a musical, four films, numerous albums, and...
7
19212
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 00000000000000001111111111111111 11111111111111111111111111111111 00000000000000000000000000000000 11111111111111110000000000000000
5
12928
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 password=CAST(@password as binary) However when I go to sql server and convert that binary field to varchar, all I get is the first letter of the password that I typed in. How do I
6
5260
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 Convert.FromBase64String seem like the closest thing I can find to what I'm looking for baked into the base class library. Can anyone suggest a better way to do this? TIA - Bob
0
8781
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8551
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8639
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7386
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4198
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4368
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2771
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2011
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1775
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.