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

1

10

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.

Defroster answered 8/2, 2016 at 13:53 Comment(1)
Is there something wrong with the information and examples in the Python documentation? See docs.python.org/2/library/…Chide
A
7

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.

Allergist answered 9/2, 2016 at 4:59 Comment(3)
Thank you. Can you explain me why is it used in networking when sending data from one computer to another? Why don't we send just plain text? And why do we see ' " ' instead of '\x22'(I know it represents its ASCII code, but what does an integer representation has got to do with ' " ')?Defroster
@shiva, A lot of protocols are raw data rather than text because it can be smaller and faster to send such things. These days, text formats are very common than they used to be, but certainly not common for very high-performance stuff.Allergist
@shiva, For convenience, easily-represented characters are represented in bytestrings by their ASCII letters rather than just their numbers. Since 0x22 maps to ", Python just uses ", since 0x71 maps to q, Python will display the string "\x71" as "q". nedbatchelder.com/text/unipain.html might provide you some orientation as to how strings work.Allergist

© 2022 - 2024 — McMap. All rights reserved.