Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Work with bytes in python

Tags:

python

arrays

I have to get bytes array and send it into socket.

The structure looks like: 1 byte + 2 bytes + 2 bytes.

First byte is number '5', second 2 bytes should be taken from variable first, third 2 bytes should be taken from variable second. What's the right way to do this in python?

id = 5      # Fill as 1 byte
first = 42  # Fill as 2 bytes
second = 58 # The same as first
like image 736
Max Frai Avatar asked Feb 16 '26 03:02

Max Frai


1 Answers

Use the struct module:

>>> import struct
>>> id, first, second = 5, 42, 58
>>> struct.pack('>bhh', id, first, second)
'\x05\x00*\x00:'

You may want to figure out if your data is a) little or big endian and b) is signed or unsigned; the example above use big-endian ordering and signed values.

The result (in python 3) is a bytes object.

like image 77
Martijn Pieters Avatar answered Feb 18 '26 16:02

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!