[Tutor] string to binary and back... Python 3
Jordan
wolfrage8765 at gmail.com
Thu Jul 19 21:59:39 CEST 2012
On 07/19/2012 09:23 PM, Prasad, Ramit wrote:
>> A question I have for the group before I respond is a option that I saw
>> that I had earlier was to ord() each element of a string and then bin()
>> that number. But since bin() produces a string I could not figure out
>> the correct way to attach two bin() outputs back together again due to
>> the leading 'b' and even if I use lstrip('b') I was not sure if that
>> would be correct?
> 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.
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.
>
>> My next hesitation is can the same or at least similar techniques be
>> applied to a file? I want to be able to work on both files and strings.
> Probably, but it depends on what you are trying to do and what
> data you are dealing with.
I just want to perform the same conversion on the file data, that is
down to binary and back to it's original state.
I was thinking I would just use the file in binary mode when I open it,
but I am not sure if that is true binary or if it is hex or something
else altogether. I think my confusion came from trying to do both files
and strings at the same time and failing back and forth.
>
> 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.
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list