Open In App

How to Convert Int to Bytes in Python?

Last Updated : 24 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The task of converting an integer to bytes in Python involves representing a numerical value in its binary form for storage, transmission, or processing. For example, the integer 5 can be converted into bytes, resulting in a binary representation like b’\x00\x05′ or b’\x05′, depending on the chosen format.

Using int.to_bytes()

.to_bytes() method is the most direct way to convert an integer to bytes. It allows specifying the byte length and byte order (big for big-endian, little for little-endian).

a = 5

res = a.to_bytes(2, 'big')  # length: 2 bytes, byte order: Big-endian
print(res)

Output
b'\x00\x05'

Explanation: Here, 2 ensures a fixed 2-byte representation, adding a leading zero-byte (\x00) for padding. ‘big’ specifies big-endian order, storing the most significant byte first.

Using struct.pack()

struct.pack() function is used for packing integers into bytes using format specifiers. The “>H” format specifies a big-endian 2-byte unsigned short, ensuring a structured binary representation.

import struct
a = 5

res = struct.pack(">H", a)  # '>H' -> big-endian Unsigned Short (2 bytes)
print(res) 

Output
b'\x00\x05'

Explanation: Here, H represents an unsigned short (2 bytes) and > ensures big-endian order, storing the most significant byte first. Since 5 is smaller than 256, a leading zero-byte (\x00) is added for proper 2-byte representation.

Using bytes()

bytes() function can be used to create a single-byte representation of an integer. This method works only for values between 0 and 255 because a single byte can store values in this range.

a = 5

res = bytes([a])  # converts single integer to a 1-byte representation
print(res)

Output
b'\x05'

Explanation:bytes([a]) converts 5 into a 1-byte object since it falls within the 0-255 range, meaning no padding is needed.

Using bytes.fromhex()

This method first converts an integer to a hex string, ensuring it is properly padded and then converts it into a bytes object. It is useful when dealing with hex-based data representation.

a = 5

res = bytes.fromhex(hex(a)[2:].zfill(2))  # ensures 2-digit hex representation
print(res)

Output
b'\x05'

Explanation: hex(a)[2:] removes the 0x prefix, .zfill(2) ensures a 2-digit hex format and bytes.fromhex() converts it into a byte object (b’\x05′) .



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg