saeed saeed - 3 months ago 16
Python Question

Packing an integer number to 3 bytes in Python

With background knowledge of C I want to serialize an integer number to 3 bytes. I searched a lot and found out I should use struct packing. I want something like this:

number = 1195855
buffer = struct.pack("format_string", number)


Now I expect buffer to be something like
['\x12' '\x3F' '\x4F']
. Is it also possible to set endianness?

Answer

It is possible, using either > or < in your format string:

import struct

number = 1195855

# Little Endian
buffer = struct.pack("<L", number)
print(buffer.hex())                # 4f3f1200

# Big Endian
buffer = struct.pack(">L", number)
print(buffer.hex())                # 00123f4f

Note, however, that you're going to have to figure out how you want to get rid of the empty byte in the buffer, since L will give you 4 bytes and you only want 3.

Something like:

# Little Endian
buffer = struct.pack("<L", number)
print(buffer[:3].hex())             # 4f3f12

# Big Endian
buffer = struct.pack(">L", number)
print(buffer[-3:].hex())            # 123f4f

would be one way.

Comments