首页 > 解决方案 > 如何使用 struct 模块转换 64 位地址?

问题描述

使用 Python 的struct模块,我可以很好地转换 32 位地址:

rp = struct.pack("<L", 0x565555c7)
# b'\xc7UUV'

但是当我尝试使用 64 位地址时:

Traceback (most recent call last):
File "<string>", line 3, in <module>
struct.error: 'L' format requires 0 <= number <= 4294967295

那么我怎么能使用结构库呢?还有哪些其他方法可用于打包 64 位地址?

标签: pythonpython-3.x

解决方案


int有一种方法可以为您做到这一点:

>>> 0x565555c7.to_bytes(8, 'big')
b'\x00\x00\x00\x00VUU\xc7'

to_bytesbytes在给定所需字节数和字节序的情况下生成一个值。相比

# 4 bytes instead of 8
>>> 0x565555c7.to_bytes(4, 'big')
b'VUU\xc7'

# 4 bytes, but little-endian instead of big-endian
>>> 0x565555c7.to_bytes(4, 'little')
b'\xc7UUV'

推荐阅读