Max Frai
Max Frai

Reputation: 64286

Work with bytes in python

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

Upvotes: 3

Views: 219

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122312

Use the struct module:

>>> import struct
>>> id, first, second = 5, 42, 58
>>> struct.pack('>bhb', id, first, second)
b'\x05\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.

Upvotes: 7

Related Questions