将 reinterpret_cast 从 C++ 转换为 Python

Convert reinterpret_cast from C++ to Python

我有这段 C++ 代码,我想将其转换为 Python:

int main() {
    char buf[21] = "211000026850KBAALHAA";
    std::cout << reinterpret_cast<const uint32_t*>(buf+12) << "\n";
    const uint32_t *num = reinterpret_cast<const uint32_t*>(buf+12);
    std::cout << num[0] << " " << num[1] << "\n";
}

打印 1094795851 1094797388。我想写一个类似的函数来输入 KBAALHAA 和输出 1094795851 1094797388。我似乎无法在 Python.

中找到等价于 reinterpret_cast 的函数

struct 模块中的 unpack_from 函数非常适合这个。

https://docs.python.org/3.9/library/struct.html#struct.unpack_from

Unpack from buffer starting at position offset, according to the format string format. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes, starting at position offset, must be at least the size required by the format, as reflected by calcsize().

这里使用的格式字符串是III 是一个 4 字节无符号整数。

import struct

string = b"211000026850KBAALHAA"
num = struct.unpack_from("II", string, 12)
print(num[0], num[1])

输出:

1094795851 1094797388