Skip to content Skip to sidebar Skip to footer

How To Efficiently Store An Int Into Bytes?

I am developing a program that uses the python 3.7 socket library to send and receive information, and I want it to be efficient network wise (doesn't need to be all that fast, I d

Solution 1:

If you want to pack numbers into bytes, you'll want the struct module.

>>> struct.pack('>H', 1024)
b'\x04\x00'

This packs the data 1024 into a single unsigned short aka uint16_t (H), in big-endian format (>). This gives the two bytes 04 00.

In practice, struct is usually used to pack a lot of data together, using longer format strings:

data = struct.pack('>bbbbHHiid', dat1, dat2, dat3...)

You probably see now why that module gets its name!

If you really only need to send a single number, you can use the built-in int.to_bytes method:

>>> (1024).to_bytes(2, 'big')
b'\x04\x00'

The first argument is the number of bytes to use, the second is the endianness.

Post a Comment for "How To Efficiently Store An Int Into Bytes?"