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 in Python? Like in C:
uint32_t number=100; array[0]=(number >>24) & 0xff; array[1]=(number >>16) & 0xff; array[2]=(number >>8) & 0xff; array[3]=number & 0xff;
Can someone show me how? It is strange to me at first to program without types.
An int value can be converted into bytes by using the method int. to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.
The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte).
To be safe, Python allocates a fixed number of bytes of space in memory for each variable of a normal integer type, which is known as int in Python. Typically, an integer occupies four bytes, or 32 bits.
Have a look at the struct
module. Probably all you need is struct.pack("I", your_int)
to pack the integer in a string, and then place this string in the message. The format string "I"
denotes an unsigned 32-bit integer.
If you want to unpack such a string to a tuple of for integers, you can use struct.unpack("4b", s)
:
>>> struct.unpack("4b", struct.pack("I", 100)) (100, 0, 0, 0)
(The example is obviously on a little-endian machine.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With