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.
unpack() This function converts the strings of binary representations to their original form according to the specified format.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With