Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert integer value to array of four bytes in python

Tags:

python

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.

like image 532
Jana Avatar asked May 31 '11 12:05

Jana


People also ask

How do you convert int to byte in Python?

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.

How do you convert int to bytes?

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).

How many bytes is an integer in Python?

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.


1 Answers

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.)

like image 118
Sven Marnach Avatar answered Oct 03 '22 10:10

Sven Marnach