Python 2: int to bytes array
Many times while working with python for industrial automation protocols where data being exchanged between your python scripts on PC and your target is in hex-decimal bytes array.
For such scenarios where your data in python script is in int or in long format, and underlying driver library used by python receives only bytes array. For such scenarios it is inevitable to convert int or long data to hex-decimal bytes array.
Python 3:
In python 3, where all numbers are int type irrespective of size of number and fortunately there is built in method i.e. int.to_bytes() to convert such numbers to bytes array.
Here is an example of converting 32 bit to byte array, ip address 192.168.1.1 is saved as int 3232235777 or 0xC0A80101 in python script
Python 2:
In python 2, where numbers can be of int or long type and conversion of such numbers without help of build in methods required some manipulation
Convert int to bytes in Python
In this tutorial, we will look at how to convert an int type object to a bytes type object in Python with the help of some examples.
How to convert int to bytes in Python?
You can use the int class method int.to_bytes() to convert an int object to an array of bytes representing that integer. The following is the syntax –
It takes the following arguments –
- length – The number of bytes to use to represent the integer. If the integer is not representable with the given number of bytes, an OverflowError is raised.
- byteorder – Determines the byte order used to represent the integer. Use ‘big’ as the byte order to have the most significant byte at the beginning of the byte array. Use ‘little’ as the byte order to have the most significant byte at the end of the byte array.
- signed – Determines wheter to use two’s compliment to represent the integer. It is an optional parameter and is False by default. Helpful in converting signed integers to bytes.
Examples
Let’s look at some examples of using the int.to_bytes() function to convert an integer to bytes.
Using ‘big’ as the byteorder
Let’s convert the integer value 7 to a byte array of length 2 and with “big” as the byteorder.
We get the returned value as bytes with the most significant byte at the beginning.
Using ‘little’ as the byteorder
Let’s use the same example as above but with “little” as the byteorder
We get the most significant byte at the end of the byte array.
Negative Integers to bytes with signed=True
If you use the default signed=False on a negative integer, you will get an OverflowError .
To convert negative integers to bytes with the int.to_bytes() function, pass signed=True . It will use two’s complement to represent the integer.
We get the bytes for the negative integer.
For more on the int.to_bytes() function, refer to its documentation.
You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Как преобразовать Int в байты на Pythonх 2 и 3
Преобразование из int в bytes является обратной операцией преобразования из bytes в int , которая представлена в последнем учебнике HowTo. Большинство представленных в статье методов преобразования байт в байты — это обратные методы преобразования байт в распечатки.
Python 2.7 и 3 Совместимый метод преобразования int в bytes
Вы можете использовать функцию pack в Python struct module для преобразования целого в байты в определенном формате.
Первым аргументом в функции struct.pack является строка формата, которая задает формат байтов, такой как длина байта, знак, порядок следования байтов (малый или большой эндиан) и т.д.
Python 3 Только int к bytes Методы преобразования
Используйте bytes для преобразования int в bytes
Как было указано в прошлой статье, bytes — это встроенный тип данных с Python 3. Вы можете легко использовать bytes для приведения целого числа 0
255 к типу данных байт.
Целое число должно быть окружено скобками, иначе получится объект размером байты, заданный параметром, инициализированным нулевым байтом , а не соответствующие ему байты.
Используйте метод int.to_bytes() Метод преобразования int в bytes
На Python3.1 введен новый метод целочисленных классов int.to_bytes() . Это метод обратного преобразования int.from_bytes() , о котором шла речь в предыдущей статье.
Первый аргумент — длина преобразованных байт данных, второй — порядок следования байт — маленький или большой, а опциональный аргумент signed определяет, используется ли дополнение двоих для представления целого числа.
Сравнение производительности
- метод bytes()
- метод struct.pack()
- метод int.to_bytes()
Мы проверим время выполнения каждого метода, чтобы сравнить их производительность, и, наконец, дадим вам рекомендацию, если вы хотите увеличить скорость выполнения вашего кода.
Python 2,3 Convert Integer to "bytes" Cleanly
I am particularly concerned with two factors: readability and portability. The second method, for Python 3, is ugly. However, I think it may be backwards compatible.
Is there a shorter, cleaner way that I have missed? I currently make a lambda expression to fix it with a new function, but maybe that’s unnecessary.
7 Answers 7
Answer 1:
To convert a string to a sequence of bytes in either Python 2 or Python 3, you use the string’s encode method. If you don’t supply an encoding parameter ‘ascii’ is used, which will always be good enough for numeric digits.
- Python 2: http://ideone.com/Y05zVY
- Python 3: http://ideone.com/XqFyOj
In Python 2 str(n) already produces bytes; the encode will do a double conversion as this string is implicitly converted to Unicode and back again to bytes. It’s unnecessary work, but it’s harmless and is completely compatible with Python 3. Answer 2:
Above is the answer to the question that was actually asked, which was to produce a string of ASCII bytes in human-readable form. But since people keep coming here trying to get the answer to a different question, I’ll answer that question too. If you want to convert 10 to b’10’ use the answer above, but if you want to convert 10 to b’\x0a\x00\x00\x00′ then keep reading.