python-3.x - 将二进制转换为字符串
问题描述
我需要转换:1010100 1101000 1101001 1110011 100000 1101001 1110011 100000 1100001 100000 1110011 1110100 1110010 1101001 1101110 110 到字符串。我已将字符串转换为二进制
text2 = 'This is a string'
res = ' '.join(format(ord(i), 'b') for i in text2)
print(res)
#output:
1010100 1101000 1101001 1110011 100000 1101001 1110011 100000 1100001 100000 1110011 1110100 1110010 1101001 1101110 1100111
现在我无法将其转换回字符串,chr 给了我一些亚洲字符:
c = ' '.join(chr(int(val)) for val in res.split(' '))
print(c)
#output:
然后我尝试 binascii 但也没有工作:
l = res.split()
print(l)
for i in l:
print (binascii.b2a_uu(bytes(i, 'utf-8')))
output:
b"',3 Q,#$P, \n"
b"',3$P,3 P, \n"
b"',3$P,3 P,0 \n"
b"',3$Q,# Q,0 \n"
b'&,3 P,# P\n'
b"',3$P,3 P,0 \n"
b"',3$Q,# Q,0 \n"
b'&,3 P,# P\n'
b"',3$P,# P,0 \n"
b'&,3 P,# P\n'
b"',3$Q,# Q,0 \n"
b"',3$Q,#$P, \n"
b"',3$Q,# Q, \n"
b"',3$P,3 P,0 \n"
b"',3$P,3$Q, \n"
b"',3$P,#$Q,0 \n"
解决方案
您需要设置base
for int
:
''.join(chr(int(val, 2)) for val in res.split(' '))
输出:
'This is a string'
推荐阅读
- typescript - 子组件中的设置器编译但引发和错误
- ios - original_purchase_date 在 latest_receipt_info 中的相同 original_transaction_id 下的不同交易具有不同的价值
- z3 - 处理 Z3 中的引用表达式
- node.js - 如何查看谁邀请了离开的用户 | 不和谐.js
- reactjs - 在 Firebase 中使用重定向 Google 登录后如何将用户重定向到特定网页?
- flutter - 为什么 snapshot.data 在 FutureBuilder 中返回 null?
- git - 如何将 git repo 迁移到新笔记本电脑
- html - 如何根据 html 中的标签和类内容选择带有正则表达式的文本?
- laravel-blade - Laravel 8 的嵌套关系访问
- python - for循环内的逻辑运算符,不起作用