我试图在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
现在返回0的字节(整型)与奇怪的交互效果更差
和:
如果
( ASCIIfication )返回该整型的整数,对我来说会方便得多;但老实说,即使是一个错误也比这种行为要好。(如果我想要这个行为--我从来没有这样做过--我希望它是一个类方法,像“bytes.zeroes(N)”一样被调用。)
有人能解释一下这种行为是从哪里来的吗?
发布于 2014-01-09 18:37:38
这就是它的设计方式--这是有意义的,因为通常情况下,你会在一个迭代器上调用bytes
,而不是一个整数:
>>> bytes([3])
b'\x03'
bytes
的docs state this和文档字符串
>>> help(bytes)
...
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
发布于 2015-05-21 21:28:46
在python 3.2中,您可以执行以下操作
>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
https://docs.python.org/3/library/stdtypes.html#int.to_bytes
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)
发布于 2014-11-14 08:25:01
您可以使用struct's pack
In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'
">“是byte-order (big-endian),"I”是format character。所以,如果你想做其他事情,你可以说得很具体:
In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'
In [13]: struct.pack("B", 1)
Out[13]: '\x01'
这在Python2和上都是一样的。
注意:反向操作(字节到整型)可以用unpack来完成。
https://stackoverflow.com/questions/21017698
复制相似问题