如何在Python中高效地进行二进制和ASCII(包括Unicode)之间的转换?
将二进制转换为 ASCII 以及反之亦然
在 Python 中,将字符串转换为其二进制表示形式非常简单。使用reduce()、lambda、ord() 和bin() 的组合,可以获得字符串的二进制等价物。但是,这种方法需要手动进行字符串拼接并映射到相应的 ASCII 值。
更简单的转换方法
对于 Python 2,可以使用 binascii 模块提供更简洁的方法:
import binascii bin(int(binascii.hexlify('hello'), 16))
该方法将[-~范围内的ASCII字符进行转换,与原代码类似。用于转换回字符串:
binascii.unhexlify('%x' % n)
Python 3.2 增强功能
在 Python 3.2 及更高版本中,字节类型提供了额外的便利:
bin(int.from_bytes('hello'.encode(), 'big'))
用于转换回字符串:
n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()
Python 中的 Unicode 支持3
要支持 Python 3 中的所有 Unicode 字符,可以使用以下函数:
def text_to_bits(text, encoding='utf-8', errors='surrogatepass'): bits = bin(int.from_bytes(text.encode(encoding, errors), 'big'))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'): n = int(bits, 2) return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding, errors) or '<pre class="brush:php;toolbar:false">import binascii def text_to_bits(text, encoding='utf-8', errors='surrogatepass'): bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'): n = int(bits, 2) return int2bytes(n).decode(encoding, errors) def int2bytes(i): hex_string = '%x' % i n = len(hex_string) return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
对于 Python 2/3 兼容性:
使用这些函数,在 Python 2 和 Python 3 中二进制和 Unicode 字符串之间的转换变得毫不费力。
以上是如何在Python中高效地进行二进制和ASCII(包括Unicode)之间的转换?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

Python3.6环境下加载pickle文件报错:ModuleNotFoundError:Nomodulenamed...

使用Scapy爬虫时管道文件无法写入的原因探讨在学习和使用Scapy爬虫进行数据持久化存储时,可能会遇到管道文�...
