Python里 int 和 bytes互转的方法
在Python3之前,一般是使用下面的方法:
>>> import struct
>>> struct.pack("B", 2)
'\x02'
>>> struct.pack(">H", 2)
'\x00\x02'
>>> struct.pack("<H", 2)
'\x02\x00'
也就是使用struct.pack方法,它实现了从int到bytes的转换。
在Python3里,也可以使用bytes转换0到255的整数,如下:
>>> bytes([2])
b'\x02`
这时候不要写成:bytes(3),这样导致下面的结果:
>>> bytes(3)
b'\x00\x00\x00'
从Python 3.1起,就可以使用int.to_bytes()来转换整数到字节数组:
>>> (258).to_bytes(2, byteorder="little")
b'\x02\x01'
>>> (258).to_bytes(2, byteorder="big")
b'\x01\x02'
>>> (258).to_bytes(4, byteorder="little", signed=True)
b'\x02\x01\x00\x00'
>>>