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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to find element by part of its id name in selenium with python(如何使用python在selenium中通过其id名称的一部分查找元素)
NoSuchElementException: Message: Unable to locate element while trying to click on the button VISA through Selenium and Python(NoSuchElementException:消息:尝试通过 Selenium 和 Python 单击 VISA 按钮时无法找到元素) - IT屋-程序员软件开发技术分
Selenium not able to click on Get Data button on using Python(Selenium 在使用 Python 时无法单击“获取数据按钮)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable with Selenium and Python(selenium.common.exceptions.ElementClickInterceptedException:消息:元素点击被拦截:元素不可点击
Selenium Compound class names not permitted(不允许使用硒化合物类名称)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element while trying to click Next button with selenium(selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:尝试使用 selenium 单