python字符串转ascii_如何二进制字符串转换为ASCII字符串在Python?

本文介绍了一个使用Python编写的简单程序,该程序能够读取二进制文件并将其转换为文本格式,再从文本格式还原回二进制。文章详细展示了如何利用Python内置函数如ord(), chr()和int()等进行数据转换,并提供了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Edit: I've now made a long if else script for it, but thanks for the 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')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值