如何在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字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)