Python: num to bytes – Education Career Blog

I want to have a byte representation of some numbers. For example, a byte array whose first byte has a meaning (0-255), the second byte another (0-255) and so on. Since string are byte arrays i can easily represent it as “aB” if I want to store 97 and 66.
Now, if i want the third and forth bytes to represent a number between 0 and 65535, how can I do?

Ps: I’m using python 2.5, so I cannot take advantage of the functions to manipulate bytes (like bytes() and bytearray()) that have been introduced lately.

edit:
0-65536 -> 0-65535

,

You want struct.

>>> import struct
>>> struct.pack('<HBB', 12345, 97, 66)
'90aB'

,

(You’ll have a bit of difficulty if you want to represent 0-65536, so I’ll assume you meant 0-65535.)

Simply store x>>8 in the one byte, and x&0xff in the other byte. You can also use Python’s struct module to pack different kinds of data into bytes.

Leave a Comment