Friday, October 3, 2025
HomeLanguagesHow to Convert Int to Bytes in Python?

How to Convert Int to Bytes in Python?

An int object can be used to represent the same value in the format of the byte. The integer represents a byte, is stored as an array with its most significant digit (MSB) stored at either the start or end of the array. 

Method 1: int.tobytes()

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.

Syntax: int.to_bytes(length, byteorder)

Arguments

length – desired length of the array in bytes .

byteorder – order of the array to carry out conversion of an int to bytes. byteorder can have values as either “little” where most significant bit is stored at the end and least at the beginning, or big, where MSB is stored at start and LSB at the end. 

Exceptions : 

OverflowError is returned in case the integer value length is not large enough to be accommodated in the length of the array. 

The following programs illustrate the usage of this method in Python : 

Python3




# declaring an integer value
integer_val = 5
  
# converting int to bytes with length 
# of the array as 2 and byter order as big
bytes_val = integer_val.to_bytes(2, 'big')
  
# printing integer in byte representation
print(bytes_val)


Output

b'\x00\x05'

Python3




# declaring an integer value
integer_val = 10
  
# converting int to bytes with length 
# of the array as 5 and byter order as 
# little
bytes_val = integer_val.to_bytes(5, 'little')
  
# printing integer in byte representation
print(bytes_val)


Output

b'\n\x00\x00\x00\x00'

Method 2: Converting integer to string and string to bytes 

This approach works is compatible in both Python versions, 2 and 3. This method doesn’t take the length of the array and byteorder as arguments. 

  • An integer value represented in decimal format can be converted to string first using the str() function , which takes as argument the integer value to be converted to the corresponding string equivalent.
  • This string equivalent is then converted to a sequence of bytes by choosing the desired representation for each character, that is encoding the string value. This is done by the str.encode() method.

Python3




# declaring an integer value
int_val = 5
  
# converting to string
str_val = str(int_val)
  
# converting string to bytes
byte_val = str_val.encode()
print(byte_val)


Output

b'5'
RELATED ARTICLES

Most Popular

Dominic
32332 POSTS0 COMMENTS
Milvus
85 POSTS0 COMMENTS
Nango Kala
6703 POSTS0 COMMENTS
Nicole Veronica
11868 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11929 POSTS0 COMMENTS
Shaida Kate Naidoo
6819 POSTS0 COMMENTS
Ted Musemwa
7080 POSTS0 COMMENTS
Thapelo Manthata
6775 POSTS0 COMMENTS
Umr Jansen
6776 POSTS0 COMMENTS