3

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

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@Ockonal: then use the '>' format marker at the start; my example now uses that.
Consider creating a Struct object (from the same module) if the byte-packing occurs repeatedly.
According to the question the variable named 'second' should be two bytes too.
@Ray: ah, indeed, I fixed my answer now. Slightly confusing wording there, first could be read as referring to the first value, but there is also a variable with the same name. The description of the structure bytes is clearer however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.