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

Prasad, Ramit ramit.prasad at jpmorgan.com
Thu Jul 19 20:53:31 CEST 2012


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

> Sorry for the long delay in getting back to you, I got called to the field.
> Thank you, I agree I do feel like I am doing too much conversion. I do
> understand the concept behind ASCII at least enough to know about ord()
> although I did for get about chr() which is ord()'s reverse function. I
> had tried to break them down to the ordinal value, but I really do want
> to get the integer and the data down to binary, as it provides an
> advantage for the overall program that I am writing. Thank you for your
> time.

Why not explain your usecase? Technically, everything is binary
on a computer so the question is why do *you* need to see the
binary form? Anyway, you can get the binary string by doing
`bin(ord(character))` and reverse it by doing 
`chr(int(binary_string,2))`. [1]

If you are doing some kind of XOR (I think your first email mentioned 
it) then you can XOR integers. Unless you are doing some kind of 
display of binary output, you usually do not need to actually see 
the binary string as most binary manipulation can be done via the 
integer value.

 [1] - Thanks to Steven.




Ramit

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