Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pack list of ints in Python

Tags:

python

struct

I have got a list that I am packing as bytes using struct module in Python. Here is my list:

[39, 39, 126, 126, 256, 258, 260, 259, 257, 126]

I am packing my list as:

encoded = struct.pack(">{}H".format(len(list)), *list)

where I pass number of elements in list as a format.

Now, I need to unpack the packed struct. For that I will need a format where I again pass number of elements. For now I am doing it like so:

struct.unpack(">{}H".format(10), encoded)

However, I can't pass it as a simple parameter to function format because that struct is then written to file that I am using for compressing image. How can I add a number of elements to file, and unpack it after?

P.S. I would like to get that 10 (in unpacking) from file itself that is packed as bytes.

like image 759
Anuar Maratkhan Avatar asked May 20 '26 02:05

Anuar Maratkhan


2 Answers

Form what I understood from the comments and questions. Maybe this will be helpful.

import struct
data = [39, 39, 126, 126, 256, 258, 260, 259, 257, 126]

encoded = struct.pack(">{}H".format(len(data)), *data)
tmp = struct.pack(">H", len(data))
encoded = tmp + encoded #appending at the start
begin = 2
try:
    size = struct.unpack(">H", encoded[0:begin])[0]
    print(size)
    print(struct.unpack(">{}H".format(size), encoded[begin:]))
except Exception as e:
    print(e)

Let me know if it helps.

like image 77
Sumit Jha Avatar answered May 21 '26 14:05

Sumit Jha


Here is my approach of adding that [number of elements] to the file:

file.write(len(compressed_list).to_bytes(3,'big'))

I allocate 3 bytes of memory for the length of compressed_list, convert it to bytes, and add it to the beginning of the file. Further, write other left parts.


Next, when I need that number, I get it from the file like so:

sz = int.from_bytes(encoded[0:3],'big')

which means that I take first three bytes from byte array read from the file, and typecast that bytes to int.

That solved my problem.

like image 34
Anuar Maratkhan Avatar answered May 21 '26 14:05

Anuar Maratkhan



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!