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

Prasad, Ramit ramit.prasad at jpmorgan.com
Thu Jul 19 22:41:32 CEST 2012


> > bin(integer).split('b')[1].zfill( multiple_of_eight )
> OK so using this: Hopefully my copy paste works this time.
> 
> bin_data = ''
> 
> for char in data:
> 
> bin_data += bin(ord(char)).split('b')[1].zfill(8)
> 
> print(bin_data)
> 
> bin_list = [bin_data[x:x + 2] for x in range(0, len(bin_data), 2)]
> 
> print(bin_list)
> 
> 
> 
> The paste looks good to me at this time.

Not to me, but I can probably figure out enough based on this.

> How do I get back to the string? If I use this:
> 
> data2 = []
> 
> for item in bin_list:
> 
> data2.append(int(item, 2))
> 
> print(data2)
> 
> 
> 
> The output is all too low of numbers for ord() to convert back to the
> correct string.
> >

Sure, this makes perfect sense to me :) (adding indent)

for char in data:
    bin_data += bin(ord(char)).split('b')[1].zfill(8)
bin_list = [bin_data[x:x + 2] for x in range(0, len(bin_data), 2)]

Why are you grabbing 2 binary digits? The only possibilities are 0,1,2,3
and none are ASCII letters. You should be grabbing 8 at a time.

bin_data = [ bin(ord(char)).split('b')[1].zfill(8) for char in data ]
bin_string = ''.join(bin_data)
bin_list = [ chr( int(char, 2) ) for char in bin_data ]

I am not really sure what you are getting at with XOR and one time
padding, but it has been a while since I have done any encryption.

I would think you could do all this by just converting everything
to int and then adding/replacing the pad in the list of ints.


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