Open In App

.to_bytes() in Python

Last Updated : 21 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, the .to_bytes() method is used to convert an integer into its byte representation. This is useful when weneed to store or transmit data in binary format.

Example: Convert the integer 10 into bytes

Python
num = 10
byte_data = num.to_bytes(2, 'big')
print(byte_data) 

Output
b'\x00\n'

Explanation:

  • 10: The integer being converted.
  • .to_bytes(2, 'big'): 2: Specifies the byte length (2 bytes). 'big': Most significant byte first (big-endian).
  • b'\x00\n': The byte representation of 10 using big-endian format.

Syntax

int.to_bytes(length, byteorder, *, signed=False)

Parameters

  • length: The number of bytes the integer should occupy.
  • byteorder: The byte order used to represent the integer. It can be: 'big': Most significant byte first (big-endian). 'little': Least significant byte first (little-endian).
  • signed: (Optional) If True, allows the representation of negative numbers. Default is False (unsigned).

Return Type

Returns a bytes object representing the integer in the specified format.

Examples of .to_bytes() method

1. Using Little-Endian

Python
num = 10
byte_rep = num.to_bytes(2, 'little')
print(byte_rep)

Output
b'\n\x00'

Explanation:

  • 10 in binary is 00001010, and in little-endian, it is represented as b'\n\x00'.
  • The b'\n\x00' output shows that 10 is stored as \n (10 in hexadecimal) followed by \x00 (a zero byte).

2. Representing Negative Numbers

Python
num = -10
byte_rep = num.to_bytes(2, 'big', signed=True)
print(byte_rep)  

Output
b'\xff\xf6'

Explanation:

  • -10 in two's complement (signed) using big-endian is represented as b'\xff\xf6'.
  • The b'\xff\xf6' output indicates that -10 is stored using two bytes where the first byte is 0xFF (representing the negative sign) and the second byte is 0xF6 (which is -10 in two's complement form).

3. Converting bytes back to integer

Python
byte_data = b'\x00\x0a'
num = int.from_bytes(byte_data, 'big')
print(num) 

Output
10

Explanation:

  • b'\x00\x0a' represents the byte sequence where the first byte is 0x00 (0 in decimal) and the second byte is 0x0a (10 in decimal).
  • Using big-endian byte order, this byte sequence is converted to the integer 10.

Article Tags :
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy