如何在python中将二进制字符串转换为ascii字符串

How to convert binary string to ascii string in python?(如何在python中将二进制字符串转换为ascii字符串?)

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

问题描述

我制作了一个小 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()

这个对我不起作用... 将二进制转换为ASCII,反之亦然

类似这个网页:http://www.roubaixinteractive.com/PlayGround/Binary_Conversion/Binary_To_Text.asp

我现在为它制作了一个很长的 if else 脚本,但感谢您的回答

推荐答案

我们来看看'hello'这个词,它是0110100001100101011011000110110001101111

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

要将其转换回字符,我们可以使用 chrint(以 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))

如果我们想将 'hello' 转换为二进制,我们可以使用 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')

这篇关于如何在python中将二进制字符串转换为ascii字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在python中将二进制字符串转换为ascii字符串

基础教程推荐