I need to send a message of bytes in Python and I need to convert an unsigned integer number to a byte array. How do you convert an integer value to an array of four bytes i
In case anyone looks at this question sometime later ...
This statement should be equivalent to the code in the original question:
>>> tuple( struct.pack("!I", number) )
('\x00', '\x00', '\x00', 'd')
And I don't think it matters what the host byte order is.
If your integers are larger than int32, you can use "!Q"
in the call to pack()
for int64 (if your system supports Q
).
And list()
or even bytearray()
will work in place of tuple()
.
Note, the result is a sequence of str
objects (each holding a single byte), not integers. If you must have a list of integers, you can do this:
[ ord(c) for c in struct.pack("!I", number) ]
[0, 0, 0, 100]
... or this:
>>> map( ord, tuple( struct.pack("!I", number) ) )
[0, 0, 0, 100]
But using map()
starts making things a bit messy.