Struct.unpack and Length of Byte Object

python

Solution

Assuming you have a byte string `data` such as:

>>> data = b'\x01\x02\x03\x04'
>>> data
'\x01\x02\x03\x04'

The length is the number of bytes (or characters) in the byte string:

>>> len(data)
4

So this is equivalent to your code:

>>> import struct
>>> struct.unpack('!2H', data)
(258, 772)

This tells the `struct` module to use the following format characters:

- `!` - use network (big endian) mode

- `2H` - unpack 2 x unsigned shorts (16 bits each)

And it returns two integers which correspond to the data we supplied:

>>> '%04x' % 258
'0102'
>>> '%04x' % 772
'0304'

All your code does is automatically calculate the number of `unsigned shorts` on the fly

>>> struct.unpack('!%sH' % int(len(data)/2), data)
(258, 772)

But the `int` convesion is unnecessary, and it shouldn't really be using the `%s` placeholder as that is for string substitution:

>>> struct.unpack('!%dH' % (len(data)/2), data)
(258, 772)

So unpack returns two integers relating to the unpacking of 2 `unsigned shorts` from the data byte str. Sum then returns the sum of these:

>>> sum(struct.unpack('!%dH' % (len(data)/2), data))
1030

Problem

I have the following code (data is a byte object): ``` v = sum(struct.unpack('!%sH' % int(len(data)/2), data)) ``` The part that confuses me is the %sH in the format string and the % int(len(data)/2 How exactly is this part of the code working? What is the length of a byte object? And what exactly is this taking the sum of?

Original source