如何在 python 中将从 0 开头的十六进制字符串转换为具有一定长度的字节



我想转换:

'01' -> x01x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00'
'0001' -> x00x01x00x00x00x00x00x00x00x00x00x00x00x00x00x00'

我尝试了这样的事情:

int(data,16).to_bytes(16, byteorder='little')

但是当字符串以"00"开头时,这不起作用。还有其他方法吗?

您可以使用bytes.fromhexbytes.ljust

>>> bytes.fromhex('01').ljust(16, b'')
b'x01x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00'
>>> bytes.fromhex('0001').ljust(16, b'')
b'x00x01x00x00x00x00x00x00x00x00x00x00x00x00x00x00'

最新更新