user3601643
user3601643

Reputation: 31

What exactly does Python's struct.pack do?

Sorry for the stupid question but,

I read the documentation and still can understand what is this function doing:

struct.pack('<L',0x01D1F23A)

Can someone explain in very childish and detailed manner what this function will do for the given input and for other inputs.

When i print the output i got ":≥╤☺", an ASCII representation of the hex values, so basically how struct.pack is hanging the hex value beside that it turns it to little endian. How does it stored in memory ? I didn't understand what does it "pack's".

Thanks.

Upvotes: 1

Views: 2674

Answers (2)

Mike Graham
Mike Graham

Reputation: 76653

It takes several pieces of data (in your case, one piece, L--a 4-byte integer) and puts them into a bytestring

>>> struct.pack('<L', 0x01D1F23A) == b'\x3A\xF2\xD1\x01'
True

Your confusion could come from several sources

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295281

The return value of this is a bytestring (in Python 3), or a standard (non-unicode) string in Python 2, showing 0x01D1F23A represented as an unsigned long in little-endian byte order.

It's "packed" inasmuch as it's stored as raw binary content -- the exact same content you'd have with a native unsigned long type stored natively in memory on a little-endian platform.

The byte order is specified by the <, and the unsigned-long type is specified by the L.

This is useful if you're trying to write a file, a network packet, or other content in a native binary format.

Upvotes: 2

Related Questions