4

I have been unable to understand the working of pack in struct in python.

For example I need to make 4 bytes of data together into one struct. Suppose the first byte has the value 4 in it while the second has 5 and then 6 and last 7. so i make it as

a = chr(4 & 0x0f)
b = chr(5 & 0x0f)
c = chr(6 & 0x0f)
d = chr(7 & 0x0f)

Now I need to pack them into a single structure using pack. How should i do it ?

I would also request to please explain in some detail as I need this not for just above example only and i need to understand how to do it.....

Here's the link to it struct

1 Answer 1

3

You can accomplish that with this

import struct
struct.pack('4B', 4, 6, 7, 8,)

struct is some kind of printf for building bytes structures is very handy when you are dealing with a low-level protocol, you can use the references of the module for the string formating, take a look at this wol script that I wrote, check out this file and how it use the struct module to build the WOL packet.

Sign up to request clarification or add additional context in comments.

1 Comment

Does 4B mean that it should be stored as 4 unsigned integer and is it equal to 'BBBB' in the same ???

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.