Struct in python

I could not understand the operation of the package in struct in python.

For example, I need to collect 4 bytes of data into one structure. Suppose the first byte has a value of 4 in it, and the second has a value of 5, then 6 and the last 7. Therefore, I do it like

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

Now I need to pack them into one structure using the package. How am I supposed to do this?

I also ask you to explain in detail, please, since I need this not only for the example above, and I need to understand how to do this .....

Here is a link to it struct

+4
source share
1 answer

You can accomplish this with

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

struct is some kind of printf for building byte structures, very convenient when you are dealing with a low level protocol, you can use module links to form a string, look at this wol script that I wrote, look at this file and how it uses structural module for creating a WOL package.

+3
source

Source: https://habr.com/ru/post/1346424/


All Articles