假设我有一个C语言的代码

union u_type
{
    uint32_t data;
    uint8_t  chunk[4];
} 32bitsdata;

32bitsdata.chunk[0] = some number;
32bitsdata.chunk[1] = some number;
32bitsdata.chunk[2] = some number;
32bitsdata.chunk[3] = some number;

printf("Data in 32 bits: %d\n", 32bitsdata.data);

我怎么能在python中做类似的事情呢?
我正在尝试读取一个二进制文件(逐字节)-它已经开始工作了,并且将每3个字节合并为一个int。heard struct可以做到这一点,但我不确定如何做到。
最好的,
亨利

最佳答案

ctypes呢?

from ctypes import (
        Union, Array,
        c_uint8, c_uint32,
        cdll, CDLL
)

class uint8_array(Array):
    _type_ = c_uint8
    _length_ = 4

class u_type(Union):
    _fields_ = ("data", c_uint32), ("chunk", uint8_array)

# load printf function from Dynamic Linked Libary libc.so.6 (I'm use linux)
libc = CDLL(cdll.LoadLibrary('libc.so.6')._name)
printf = libc.printf

if __name__ == "__main__":
    # initialize union
    _32bitsdata = u_type()
    # set values to chunk
    _32bitsdata.chunk[:] = (1, 2, 3, 4)
    # and print it
    printf(b"Data in 32 bits: %d\n", _32bitsdata.data)

10-04 20:55