Python int to byte list

Python int to byte list

Last updated: Jun 23, 2023
Reading time · 3 min

banner

# Table of Contents

# How to convert Int to Bytes in Python

Use the int.to_bytes() method to convert an integer to bytes in Python.

The method returns an array of bytes representing an integer.

Copied!
num = 2048 my_bytes = num.to_bytes(2, byteorder='big') print(my_bytes) # 👉️ b'\x08\x00'

convert int to bytes in python

If your integer is not stored in a variable, make sure to wrap it in parentheses before calling to_bytes() .

Copied!
my_bytes = (2048).to_bytes(2, byteorder='big') print(my_bytes) # 👉️ b'\x08\x00'

The int.to_bytes method returns an array of bytes representing an integer.

The integer is represented using length bytes and defaults to 1 .

An OverflowError is raised if the integer cannot be represented using the given number of bytes.

Copied!
my_bytes = (1024).to_bytes(2, byteorder='big') print(my_bytes) # 👉️ b'\x04\x00' my_bytes = (1024).to_bytes(10, byteorder='big') print(my_bytes) # 👉️ b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'

convert int to bytes specifying length

The second argument we passed to the to_bytes() method determines the byte order that is used to represent the integer.

The byteorder argument defaults to big .

If the byteorder argument is set to big , then the most significant byte is at the beginning of the byte array.

If you set the byteorder argument to little , the most significant byte is at the end of the byte array.

Copied!
my_bytes = (1024).to_bytes(2, byteorder='little') print(my_bytes) # 👉️ b'\x00\x04' my_bytes = (1024).to_bytes(10, byteorder='little') print(my_bytes) # 👉️ b'\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00'

set byteorder to little

# Creating a reusable function to convert an integer to bytes and vice versa

You can also create a reusable function that converts integers to bytes.

Copied!
def int_to_bytes(integer): return integer.to_bytes((integer.bit_length() + 7) // 8, 'big') print(int_to_bytes(65)) # 👉️ b'A' print(int_to_bytes(1024)) # 👉️ b'\x04\x00' print(int_to_bytes(2048)) # 👉️ b'\x08\x00'

The int_to_bytes function takes an integer as a parameter and converts it to a bytes object.

Conversely, if you need to convert a bytes object to an integer, use the int.from_bytes() method instead.

Copied!
def int_from_bytes(bytes_obj): return int.from_bytes(bytes_obj, byteorder='big') print(int_from_bytes(b'A')) # 👉️ b'A' print(int_from_bytes(b'\x04\x00')) # 👉️ b'\x04\x00' print(int_from_bytes(b'\x08\x00')) # 👉️ b'\x08\x00'

The int.from_bytes() method returns the integer represented by the given byte array.

The first argument the method takes must be a bytes-like object or an iterable that produces bytes.

The byteorder argument determines which byte order is used to represent the integer.

The default value is big which means that the most significant byte is at the beginning of the byte array.

If the byteorder argument is set to «little» , then the most significant byte is at the end of the byte array.

# Converting signed (negative) integers to bytes in Python

The examples above only work for unsigned (non-negative integers).

If you need to convert signed integers to bytes, use the following function instead.

Copied!
def int_to_bytes(integer): return integer.to_bytes( length=(8 + (integer + (integer 0)).bit_length()) // 8, byteorder='big', signed=True ) print(int_to_bytes(-1024)) # 👉️ b'\xfc\x00' print(int_to_bytes(-2048)) # 👉️ b'\xf8\x00'

Calculating the length argument when converting signed (negative) integers to bytes is a bit more complicated.

The signed argument determines whether two’s complement is used to represent the integer.

If signed is False and a negative integer is supplied, an OverflowError is raised.

By default, the signed argument is set to False .

The following function can be used if you need to convert signed bytes to integers.

Copied!
def int_from_bytes(binary_data): return int.from_bytes(binary_data, byteorder='big', signed=True) print(int_from_bytes(b'\xfc\x00')) # -1024 print(int_from_bytes(b'\xf8\x00')) # -2048

The signed argument indicates whether two’s complement is used to represent the integer.

# Converting the Integer to a String and then Bytes

If you need to convert the integer to a string and then bytes, use the str.encode method.

Copied!
num = 2048 my_bytes = str(num).encode(encoding='utf-8') print(my_bytes) # 👉️ b'2048'

We passed the integer to the str class to convert it to a string and then used the str.encode() method to convert the string to bytes.

The same can be achieved by using the bytes class.

Copied!
num = 2048 my_bytes = bytes(str(num), encoding='utf-8') print(my_bytes) # 👉️ b'2048'

If you need to convert the bytes object back to an integer, use the bytes.decode method and the int() class.

Copied!
num = 2048 my_bytes = str(num).encode(encoding='utf-8') print(my_bytes) # 👉️ b'2048' my_int = int(my_bytes.decode(encoding='utf-8')) print(my_int) # 👉️ 2048

The bytes.decode() method converts the bytes object to a string.

The last step is to use the int() class to convert the string to an integer.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

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 –

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

# int to bytes int.to_bytes(length, byteorder, signed)

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.

# integer variable num = 7 # integer to bytes num_bytes = num.to_bytes(2, byteorder='big') # display result and type print(num_bytes) print(type(num_bytes))

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

# integer variable num = 7 # integer to bytes num_bytes = num.to_bytes(2, byteorder='little') # display result and type print(num_bytes) print(type(num_bytes))

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 .

# integer variable num = -7 # integer to bytes num_bytes = num.to_bytes(2, byteorder='big') # display result and type print(num_bytes) print(type(num_bytes))
--------------------------------------------------------------------------- OverflowError Traceback (most recent call last) Input In [11], in 2 num = -7 3 # integer to bytes ----> 4 num_bytes = num.to_bytes(2, byteorder='big') 5 # display result and type 6 print(num_bytes) OverflowError: can't convert negative int to unsigned

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.

# integer variable num = -7 # integer to bytes num_bytes = num.to_bytes(2, byteorder='big', signed=True) # display result and type print(num_bytes) print(type(num_bytes))

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.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

Как преобразовать Int в байты на Pythonх 2 и 3

Как преобразовать Int в байты на Pythonх 2 и 3

  1. Python 2.7 и 3 Совместимый метод преобразования int в bytes
  2. Python 3 Только int к bytes Методы преобразования
  3. Сравнение производительности

Преобразование из int в bytes является обратной операцией преобразования из bytes в int , которая представлена в последнем учебнике HowTo. Большинство представленных в статье методов преобразования байт в байты — это обратные методы преобразования байт в распечатки.

Python 2.7 и 3 Совместимый метод преобразования int в bytes

Вы можете использовать функцию pack в Python struct module для преобразования целого в байты в определенном формате.

>>> import struct >>> struct.pack("B", 2) '\x02' >>> struct.pack(">H", 2) '\x00\x02' >>> struct.pack(", 2) '\x02\x00' 

Первым аргументом в функции 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() , о котором шла речь в предыдущей статье.

>>> (258).to_bytes(2, byteorder="little") b'\x02\x01' >>> (258).to_bytes(2, byteorder="big") b'\x01\x02' >>> (258).to_bytes(4, byteorder="little", signed=True) b'\x02\x01\x00\x00' >>> (-258).to_bytes(4, byteorder="little", signed=True) b'\xfe\xfe\xff\xff' 

Первый аргумент — длина преобразованных байт данных, второй — порядок следования байт — маленький или большой, а опциональный аргумент signed определяет, используется ли дополнение двоих для представления целого числа.

Сравнение производительности

Мы проверим время выполнения каждого метода, чтобы сравнить их производительность, и, наконец, дадим вам рекомендацию, если вы хотите увеличить скорость выполнения вашего кода.

>>> import timeint >>> timeit.timeit('bytes([255])', number=1000000) 0.31296982169325455 >>> timeit.timeit('struct.pack("B", 255)', setup='import struct', number=1000000) 0.2640925447800839 >>> timeit.timeit('(255).to_bytes(1, byteorder="little")', number=1000000) 0.5622947660224895 

Поэтому, пожалуйста, используйте функцию struct.pack() для выполнения преобразования в байты, чтобы получить наилучшую производительность исполнения, хотя она уже внедрена в ветку Python 2.

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

Сопутствующая статья — Python Bytes

Источник

Читайте также:  Beginning java 8 apis extensions and libraries
Оцените статью