python - 在 Python 3 中将 int 转换为字节

标签 python python-3.x

我试图在 Python 3 中构建这个字节对象:

b'3\r\n'

所以我尝试了明显的(对我来说),并发现了一个奇怪的行为:

>>> bytes(3) + b'\r\n'
b'\x00\x00\x00\r\n'

显然:

>>> bytes(10)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

在阅读文档时,我一直无法看到任何关于字节转换为何以这种方式工作的指针。但是,我确实在这个 Python 问题中发现了一些关于将 format 添加到字节的令人惊讶的消息(另见 Python 3 bytes formatting):

http://bugs.python.org/issue3982

This interacts even more poorly with oddities like bytes(int) returning zeroes now

和:

It would be much more convenient for me if bytes(int) returned the ASCIIfication of that int; but honestly, even an error would be better than this behavior. (If I wanted this behavior - which I never have - I'd rather it be a classmethod, invoked like "bytes.zeroes(n)".)

有人能解释一下这种行为的来源吗?

最佳答案

从 python 3.2 你可以使用 to_bytes :

>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
def int_to_bytes(x: int) -> bytes:
    return x.to_bytes((x.bit_length() + 7) // 8, 'big')
    
def int_from_bytes(xbytes: bytes) -> int:
    return int.from_bytes(xbytes, 'big')

因此,x == int_from_bytes(int_to_bytes(x))。 请注意,上述编码仅适用于无符号(非负)整数。

对于有符号整数,位长计算起来有点棘手:

def int_to_bytes(number: int) -> bytes:
    return number.to_bytes(length=(8 + (number + (number < 0)).bit_length()) // 8, byteorder='big', signed=True)

def int_from_bytes(binary_data: bytes) -> Optional[int]:
    return int.from_bytes(binary_data, byteorder='big', signed=True)

关于python - 在 Python 3 中将 int 转换为字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21017698/

相关文章:

python - 值错误 : Must pass DataFrame with boolean values only

python - 限制 python 中组合/排列的数量

python - 链接器错误 : C/C++ Extensions for python

不同文件中的python相同模块

python - 用多个键值对展平字典列表

python - 如何将 .txt 文件解析为 .xml?

python - 在 python setup.py 中,如何允许用户在不先进行构建的情况下安装我的模块文件?

python - 如何确定跨键盘的最佳路线

python-3.x - 如何使用 Starlette 框架处理 JSON 请求体

python - 在python中缓存函数的最后k个结果