Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert binary string to ascii string in python? [duplicate]

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 reads the files like this:

f_bin = open(bin_file,"rb")
to_bin_data = f_bin.read()
bin_data = bin(reduce(lambda x, y: 256*x+y, (ord(c) for c in to_bin_data), 0))
f_bin.close()

this one doesen't work for me... Convert binary to ASCII and vice versa

Something like this webpage: http://www.roubaixinteractive.com/PlayGround/Binary_Conversion/Binary_To_Text.asp

Edit: I've now made a long if else script for it, but thanks for the answers

like image 374
user1469729 Avatar asked Jul 22 '12 09:07

user1469729


People also ask

How to convert a string to ASCII in Python?

This tutorial will introduce some methods to convert a string into ASCII values in Python. We can use the for loop and the ord () function to get the ASCII value of the string. The ord () function returns the Unicode of the passed string. It accepts 1 as the length of the string.

How to convert a string to binary in Python?

Data conversion have always been widely used utility and one among them can be conversion of a string to it’s binary equivalent. Let’s discuss certain ways in which this can be done. Method #1 : Using join () + ord () + format () The combination of above functions can be used to perform this particular task.

How to convert character to string in Python 3?

Method #1 : Using join () + ord () + format () The combination of above functions can be used to perform this particular task. The ord function converts the character to it’s ASCII equivalent, format converts this to binary number and join is used to join each converted character to form a string. # Python3 code to demonstrate working of

How do I use binascii to convert binary to ASCII?

The binascii module contains a number of methods to convert between binary and various ASCII-encoded binary representations. Normally, you will not use these functions directly but use wrapper modules like uu , base64, or binhex instead.


1 Answers

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')
like image 161
Jon Clements Avatar answered Sep 21 '22 00:09

Jon Clements