473,385 Members | 1,942 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,385 software developers and data experts.

convert a long string in binary

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 several books, as well as launching the
members to individual stardom.

The television series, broadcast by the BBC from 1969 to 1974, was
conceived, written and performed by Graham Chapman, John Cleese
(1969-1973), Terry Gilliam, Eric Idle, Terry Jones and Michael Palin.
Loosely structured as a sketch show, but with a highly innovative
stream-of-consciousness approach (aided by Terry Gilliam's
animations), it pushed the boundaries of what was then considered
acceptable, both in terms of style and content.
"""

string = binary(string)
print string
// 01010101010101
i 'am searching for something like the binary function (taht doesn't
exist) to convert my string directly in binary.

Regards
Bussiere
Aug 20 '06 #1
3 3108
bussiere maillist:
i've got a very long string
and i wanted to convert it in binary
Not much tested:

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

def toBase2(number):
if number < 16:
return "0000" + _nibbles["%X" % number]
else:
d1, d2 = "%X" % number
return _nibbles[d1] + _nibbles[d2]

convbin = dict((chr(i), toBase2(i)) for i in xrange(256))

def binary(s):
return "".join(convbin[c] for c in s)

print binary("testing string")

Surely there are ways to make it shorter (But it's fast enough).

Bye,
bearophile

Aug 20 '06 #2

bussiere maillist wrote:
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 several books, as well as launching the
members to individual stardom.

The television series, broadcast by the BBC from 1969 to 1974, was
conceived, written and performed by Graham Chapman, John Cleese
(1969-1973), Terry Gilliam, Eric Idle, Terry Jones and Michael Palin.
Loosely structured as a sketch show, but with a highly innovative
stream-of-consciousness approach (aided by Terry Gilliam's
animations), it pushed the boundaries of what was then considered
acceptable, both in terms of style and content.
"""

string = binary(string)
print string
// 01010101010101
i 'am searching for something like the binary function (taht doesn't
exist) to convert my string directly in binary.
The gmpy module can convert numbers to binary strings:

import gmpy

s = """
Yes, well, of course that's just the sort of
blinkered philistine pig ignorance I've come
to expect from you non-creative garbage.
"""

ss = ''
for c in s:
sb = gmpy.digits(ord(c),2) #convert to binary string
sb = '0'*(8-len(sb)) + sb #add leading 0's
ss += sb

print ss

00001010010110010110010101110011001011000010000001 11011101100101011011000110110000101100001000000110 11110110011000100000011000110110111101110101011100 10011100110110010100100000011101000110100001100001 01110100001001110111001100100000011010100111010101 11001101110100001000000111010001101000011001010010 00000111001101101111011100100111010000100000011011 11011001100000101001100010011011000110100101101110 01101011011001010111001001100101011001000010000001 11000001101000011010010110110001101001011100110111 01000110100101101110011001010010000001110000011010 01011001110010000001101001011001110110111001101111 01110010011000010110111001100011011001010010000001 00100100100111011101100110010100100000011000110110 11110110110101100101000010100111010001101111001000 00011001010111100001110000011001010110001101110100 00100000011001100111001001101111011011010010000001 11100101101111011101010010000001101110011011110110 11100010110101100011011100100110010101100001011101 00011010010111011001100101001000000110011101100001 01110010011000100110000101100111011001010010111000 001010

Regards
Bussiere
Aug 20 '06 #3
Le dimanche 20 août 2006 13:55, be************@lycos.com a écrit*:
bussiere maillist:
i've got a very long string
and i wanted to convert it in binary

Not much tested:

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

def toBase2(number):
if number < 16:
return "0000" + _nibbles["%X" % number]
else:
d1, d2 = "%X" % number
return _nibbles[d1] + _nibbles[d2]

convbin = dict((chr(i), toBase2(i)) for i in xrange(256))

def binary(s):
return "".join(convbin[c] for c in s)

print binary("testing string")

Surely there are ways to make it shorter (But it's fast enough).
Maybe this one is more elegant :

In [305]: trans = {}

In [306]: for i in range(256) :
.....: trans[chr(i)] = ''.join(i & 2**j and '1' or '0'
.....: for j in reversed(range(8)))
.....:

In [307]: trans['a']
Out[307]: '01100001'

In [308]: trans['\xee']
Out[308]: '11101110'

In [309]: print ''.join(trans[e] for e in 'test string')
01110100011001010111001101110100001000000111001101 11010001110010011010010110111001100111

Bye,
bearophile
--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
Aug 22 '06 #4

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

Similar topics

2
by: Mel WEaver | last post by:
Hello, I have the following delphi structure for a binary file. I'm looking for idea how to read this file. Mel type TMenuDataStruct = packed record exename : string;
3
by: dale zhang | last post by:
Hi, I am trying to read an image from MS Access DB based on the following article: http://www.vbdotnetheaven.com/Code/Sept2003/2175.asp The article author is using PictureBox for windows...
4
by: dale zhang | last post by:
Hi, I am trying to save and read an image from MS Access DB based on the following article: http://www.vbdotnetheaven.com/Code/Sept2003/2175.asp Right now, I saved images without any...
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.
2
by: yxq | last post by:
There are 8 bytes binary value stored date and time in Registry. 84 8B D7 DF 8B 28 C5 01 I want to convert the binary value to date using VB.NET. Dim a As FILETIME a.dwHighDateTime = 29698187...
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...
8
by: te509 | last post by:
Hi guys, does anybody know how to convert a long sequence of bits to a bit-string? I want to avoid this: '949456129574336313917039111707606368434510426593532217946399871489' I would...
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...
22
by: xiao | last post by:
Can I fullfill this task? Using fred and fwrite?
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
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,...

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.