Python:结构模块打包整数数组

2024-10-01 07:29:34 发布

您现在位置:Python中文网/ 问答频道 /正文

在打包struct时,我通常这样做

假设我有这样的结构:

struct test {
unsigned int Id;
unsigned int Member1;
unsigned int Member2[2];  
unsigned int Member3[3];
};

test_values = (1,20,1,2,3,4,5)
vaultmap = struct.pack('IIIIIII',*test_values)

如果数组的大小很小,这个方法是可以的,但是如果它是一个更大的数字,比如512,我发现这种方法是有限制的,因为我必须说i 512次,并相应地初始化值。有什么方法可以避免这种情况吗。在

如果我有char sam[512],我们可以用512s,一些类似的东西,我正在寻找。我使用的是python2.4

512I建议有效,但我应该如何初始化数组。我想我不必输入512个整数,比如array_values=(1,1,1,1。。。。。。高达512)肯定有办法做到这一点。如果我使用数组,我会得到一个错误,说integer expected。在


Tags: 方法testid数组结构structpackint
1条回答
网友
1楼 · 发布于 2024-10-01 07:29:34

structdocumentation中有一种方法可以做到这一点。在

A format character may be preceded by an integral repeat count. For example, the format string '4h' means exactly the same as 'hhhh'.

所以在代码中,它看起来像:

# test_values is a list of 512 integers
vaultmap = struct.pack('512I',*test_values)

但是请注意,与字符串不同,所有512都是独立的数字(不是单个数组的一部分)。以后可以使用python操作将它们像数组一样处理。在

For the 's' format character, the count is interpreted as the size of the string, not a repeat count like for the other format characters;

相关问题 更多 >