int 和 字节 相互转换

In [10]: n = 0xf1f2

In [11]: bin(n)
Out[11]: '0b1111000111110010'

In [12]: n.bit_length()
Out[12]: 16

In [14]: n.to_bytes((n.bit_length() + 7) //8, 'little')
Out[14]: b'\xf2\xf1'

In [15]: n = 0x31f1

In [16]: n.to_bytes((n.bit_length() + 7) //8, 'little')
Out[16]: b'\xf11'

In [17]: type(n.to_bytes((n.bit_length() + 7) //8, 'little'))
Out[17]: bytes

In [18]: n.to_bytes((n.bit_length() + 7) //8, 'little').hex()
Out[18]: 'f131'

In [21]: n.to_bytes((n.bit_length() + 7) //8, 'big').hex()
Out[21]: '31f1'

In [49]: print(' '.join([hex(ch) for ch in n.to_bytes((n.bit_length()+7) // 8,'little')]))
0xf1 0x31

In [65]: print([hex(ch).replace('0x','') for ch in n.to_bytes((n.bit_length()+7) // 8,'little')])
['f1', '31']

In [40]: print(''.join([hex(byte).replace('0x', r'\x')for byte in n.to_bytes((n.bit_length() + 7) // 8, 'little')]))
\xf1\x31

你可能感兴趣的:(int 和 字节 相互转换)