Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : struct module packing integer array

Tags:

python

c

While packing struct, i usually do this

Suppose i have a structure like:

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)

This approach is ok if the size of the array is small, but if it is a larger number say 512 , i find this approach as limiting as I have to say I 512 times and accordingly initialize the values. Is there any way to avoid this like we have for char.

if i have char sam[512] , we can use 512s , Some thing similar to this, I am looking for. I am using python 2.4

512I suggestion worked, but how should i initialize the array. I dont think i have to enter 512 integers like array_values = (1,1,1,1 ...... upto 512) there definitely should be some way to do that. If I use an array , I am getting error saying integer expected.

like image 239
Vijay Avatar asked Oct 28 '25 07:10

Vijay


1 Answers

In the struct documentation there is a way to do it.

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

So in code- it will look like:

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

Note however, that unlike strings, all 512 are independent numbers (not part of a single array). You could use python manipulation to treat them like array later.

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;

like image 52
tmrlvi Avatar answered Oct 30 '25 20:10

tmrlvi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!