如何二进制字符串转换为ASCII字符串在Python? [英] How to convert binary string to ascii string in python?

查看:638
本文介绍了如何二进制字符串转换为ASCII字符串在Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个小的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 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()

这个doesen't我... <工作href=\"http://stackoverflow.com/questions/7396849/convert-binary-to-ascii-and-vice-versa-python\">Convert二进制ASCII,反之亦然(Python)的

this one doesen't work for me... Convert Binary to ASCII and vice versa (Python)

事情是这样的网页:的http://www.roubaixinteractive.com/PlayGround/Binary_Conversion/Binary_To_Text.asp

编辑:我现在已经做了一个很长的if else脚本,但感谢您的答案

推荐答案

让我们走字'你好',这是 0110100001100101011011000110110001101111

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

要翻译这回我们可以使用 CHR INT (为2基地)和一些字符列表切片...

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

如果我们要采取'你好',并将其转换为二进制我们可以使用 ORD 和字符串格式化...

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')

这篇关于如何二进制字符串转换为ASCII字符串在Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆