Skip to content Skip to sidebar Skip to footer

How To Convert Binary String To Ascii String In Python?

I've made a little python program that reads binary from a file and stores it to a text file, read the text file and store the binary. But, I can't get the binary to work... it rea

Solution 1:

Let's take the word 'hello' which is 0110100001100101011011000110110001101111

To translate that back to characters we can use chr and int (with a base of 2) and some list slicing...

''.join(chr(int(bin_text[i:i+8], 2)) for i in xrange(0, len(bin_text), 8))

If we wanted to take 'hello' and convert it to binary we can use ord and string formatting...

''.join('{:08b}'.format(ord(c)) for c in'hello')

Solution 2:

Maybe you can use built-in functions:

>>>myString = "hello">>>ba = bytearray(myString)>>>ba[0]
104
>>>bin(ba[0])
'0b1101000'

Split the 0b:

>>> bin(ba[0]).split('b')[1]
'1101000'

or

>>> bin(ba[0])[2:]
'1101000'

I'll hope you can solve your problem with the snippets! :)

Solution 3:

I use the struct module:

importstructbuf=struct.unpack('c',to_bin_data) # for one character
buf=struct.unpack('s',to_bin_data) # for a string 

edit: sorry, misunderstood the question... This works for binary data, not for strings of binary representaion of characters.

Post a Comment for "How To Convert Binary String To Ascii String In Python?"