Alex Johnson
Alex Johnson

Reputation: 534

How to change one byte int to two bytes in Python?

I am making a basic server/client program, and I am making the client in Python. I have to format the message before I send it. The first field is for message length. I can compute the message length, but I need to store the value in the first two bytes of my bytearray. If the message length is less than 256, it should be only one byte. How can I force the number to be 2 bytes without just tacking a 0x00 onto the front?

Upvotes: 0

Views: 865

Answers (1)

Adam Rosenfield
Adam Rosenfield

Reputation: 400384

Use the struct module. For example, to pack an integer into an unsigned two-byte value in network order (big-endian), you would do this:

> my_value = 1234
> packed_bytes = struct.pack('>H', my_value)
> print packed_bytes
'\x04\xd2'

Upvotes: 2

Related Questions