我试图在 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/