Unpack binary data with python
Asked Answered
M

3

14

I would like to unpack an array of binary data to uint16 data with Python.

Internet is full of examples using struct.unpack but only examples dealing with binary array of size 4.

Most of these examples are as follow (B is a binary array from a file)

U = struct.unpack("HH",B[0:4]);

So i tried to unpack an array of size 6:

U = struct.unpack("HHH",B[0:6]);

It works.

But how to do if I want to unpack an array of size L (L is pair)? I tried that:

U = struct.unpack("H"*(L/2),B[0:L]);

but it doesn't work, prompter gives me an error (for L=512 for example):

struct.error: unpack requires a string argument of length 512

This message is strange because if i want to unpack a binary array to uint16, I need a string "HHH...HHH" of half size of this array...

I would be very grateful if someone could provide me with some help.


I progress a little bit... In fact, i tried:

U = struct.unpack("H"*8,B[0:8]); 

It works.

U = struct.unpack("H"*10,B[0:10]);

It works.

U = struct.unpack("H"*222,B[0:444]);

It still works

U = struct.unpack("H"*223,B[0:446]);

It doesn't work! and it never works for size bigger than 446

Hope it will help anyone to answer me.


@MarkRansom I checked len(B) and in fact, the length is 444. I was so sure that B is an array of size 512 because B comes from : B = f.read(512) where F is a 8000-bytes-size file. So a problem with read()... Thanks for this answer! But if someone has a help to unpack binary array of size L, i would be grateful

Mopes answered 15/11, 2012 at 16:12 Comment(6)
It would be better if you would do copy & paste. I don't think you examples work: string indexing works with [], not with (). So what do you really do?Pardue
Did you check the length of your B? Is it possible that it hasn't 512 bytes?Pardue
Print len(B), it will probably be illuminating.Caton
struct.unpack_from("H", B) doesn't work? maybe you'll need to write: struct.unpack_from("%dH"%(len(B)/2), B)Gerena
B[0:446] == B[0:444] if len(B) is 444. Past 444 your string is too short.Thirtieth
from file.read() docs: "Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes)." i.e., f.read(512) can return less than 512 bytes.Nuzzle
M
13

Use array.fromstring or array.fromfile (see http://docs.python.org/2/library/array.html ):

import array
U = array.array("H")
U.fromstring(B)
Metempirics answered 15/11, 2012 at 16:59 Comment(0)
L
9

Variable length version of the same thing:

n = 999
U = struct.unpack(str(n)+"H", B)
Leucoderma answered 22/7, 2015 at 23:25 Comment(0)
Z
5

If you want to unpack n elements from binary data, you specify the number of elements together with the datatype. For n=999:

U = struct.unpack("999H", B)
Zia answered 7/7, 2014 at 8:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.