Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When/why should I use struct library in python to pack and unpack?

I cant understand when should I use pack and unpack functions in struct library in python? I also cant understand how to use them? After reading about it, what I understood is that they are used to convert data into binary. However when I run some examples like:

>>> struct.pack("i",34)
'"\x00\x00\x00'

I cant make any sense out of it. I want to understand its purpose, how these conversions take place, what does '\x' and other symbols represent/mean and how does unpacking work.

like image 202
shiva Avatar asked Feb 08 '16 13:02

shiva


People also ask

What does struct unpack do in Python?

unpack() This function converts the strings of binary representations to their original form according to the specified format.

Why struct is used in Python?

The module struct is used to convert the native data types of Python into string of bytes and vice versa. We don't have to install it. It's a built-in module available in Python3. The struct module is related to the C languages.

What is struct library?

Source code: Lib/struct.py. This module performs conversions between Python values and C structs represented as Python bytes objects. This can be used in handling binary data stored in files or from network connections, among other sources.

What does struct Calcsize do?

struct. calcsize('P') calculates the number of bytes required to store a single pointer -- returning 4 on a 32-bit system and 8 on a 64-bit system.


1 Answers

I cant understand when should I use pack and unpack functions in struct library in python?

Then you probably don't have cause to use them.

Other people deal with network and file formats that have low-level binary packing, where struct can be very useful.

However when I run some examples like:

>>> struct.pack("i",34)
'"\x00\x00\x00'

I cant make any sense out of it.

The \x notation is for representing individual bytes of your bytes object using hexadecimal. \x00 means that the byte's value is 0, \x02 means that byte's value is 2, \x10 means that that bytes value is 16, etc. " is byte 34, so we see a " instead of \x22 in this view of the string, but '\x22\x00\x00\x00' and '"\x00\x00\x00' are the same string

http://www.swarthmore.edu/NatSci/echeeve1/Ref/BinaryMath/NumSys.html might help you with some background if that is the level you need to understand numbers at.

like image 125
Mike Graham Avatar answered Sep 20 '22 17:09

Mike Graham