maridlhr maridlhr - 1 month ago 18
Python Question

Arbitrary byte value in struct.pack()

I am trying to understand how struct work?

I have two confusions :

how struct is different from * and ** or *args and **kwargs ? where should i use struct and where should i use * and ** ?

My code is :

list(b'stackoverflow')
[115, 116, 97, 99, 107, 111, 118, 101, 114, 102, 108, 111, 119]


second doubt is suppose if someone send me this code :

[115, 116, 97, 99, 107, 111, 118, 101, 114, 102, 108, 111, 119]


i have to read it after unpacking it so general way is :

>>> struct.pack(b'bbbbbbbbbbbbb',115, 116, 97, 99, 107, 111, 118, 101, 114, 102, 108, 111, 119)


but i suppose i sentence is too long and i don't want to add many "bbbbbb" as argument so how can i use something which automatically detect the length of sentence ? something like

struct.pack(b'*magic',115, 116, 97, 99, 107, 111, 118, 101, 114, 102, 108, 111, 119)


can we do it?

Answer

The struct module has nothing to do with argument passing, so I simply can't guess what you're asking about in the first part.

To your second question, you shouldn't be using struct at all for that purpose. What you want is a bytes object corresponding to the list of little integers, and that's very easy to get:

>>> somelist = [115, 116, 97, 99, 107, 111, 118, 101, 114, 102, 108, 111, 119]
>>> bytes(somelist)
b'stackoverflow'

If for some reason you're determined to use struct.pack instead for this purpose, then this is the easiest way:

>>> struct.pack("b" * len(somelist), *somelist)
b'stackoverflow'