[Tutor] string to binary and back... Python 3

Prasad, Ramit ramit.prasad at jpmorgan.com
Thu Jul 19 00:15:54 CEST 2012


> OK so I have been trying for a couple days now and I am throwing in the
> towel, Python 3 wins this one.
> I want to convert a string to binary and back again like in this
> question: Stack Overflow: Convert Binary to ASCII and vice versa
> (Python)
> <http://stackoverflow.com/questions/7396849/convert-binary-to-ascii-and-vice-
> versa-python>
> But in Python 3 I consistently get  some sort of error relating to the
> fact that nothing but bytes and bytearrays support the buffer interface
> or I get an overflow error because something is too large to be
> converted to bytes.
> Please help me and then explian what I am not getting that is new in
> Python 3. I would like to point out I realize that binary, hex, and
> encodings are all a very complex subject and so I do not expect to
> master it but I do hope that I can gain a deeper insight. Thank you all.

[ snip program ]

> data = bin(int(binascii.hexlify(bytes(data, 'UTF-8')), 16))
> data = binascii.unhexlify('%x' % data)

[ more snipping ]

> wolfrage at lm12-laptop02 ~/Projects $ python3 test_script.py
> Bit Length: 134
> 0b10101000110010101110011011101000110100101101110011001110010000001011000010011110101001000100000010000010110011101100001011010010110111000100001
> 7351954002991226380810260999848996570230305
> Traceback (most recent call last):
> File "test_script.py", line 24, in <module>
> data = binascii.unhexlify('%x' % data)
> TypeError: 'str' does not support the buffer interface

I think your basic problem is too much conversion because you do not
understand the types. A string is represented by a series of bytes
which are binary numbers. Do you understand the concept behind ASCII?
Each letter has a numeric representation that are sequential.
So the string 'abcd' is equivalent to a series of bytes 65,66,67,68.
It is not equivalent to 65666768 or 65+66+67+68. So your first
task is to convert each character to the numeric equivalent and store
them in a list. Once you have them converted to a list of integers,
you can create another list that is a list of characters.

Look at the functions chr and ord here
( http://docs.python.org/py3k/library/functions.html )

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list