Skip to content
Related Articles

Related Articles

How to Convert Bytes to Int in Python?

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 17 Nov, 2022
Improve Article
Save Article

A bytes object can be converted to an integer value easily using Python. Python provides us various in-built methods like from_bytes() as well as classes to carry out this interconversion.

int.from_bytes() method

A byte value can be interchanged to an int value by using the int.from_bytes() method. This method requires at least Python 3.2 and has the following syntax : 

Syntax: int.from_bytes(bytes, byteorder, *, signed=False)

Parameters:

  • bytes – A byte object 
  • byteorder – Determines the order of representation of the integer value. 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. Big byte order calculates the value of an integer in base 256. 
  • signed – Default value – False . Indicates whether to represent 2’s complement of a number. 

Returns – an int equivalent to the given byte

The following snippets indicate the conversion of byte to int object. 

Example 1:

Python3




# declaring byte value
byte_val = b'\x00\x01'
 
# converting to int
# byteorder is big where MSB is at start
int_val = int.from_bytes(byte_val, "big")
 
# printing int equivalent
print(int_val)

Output:

1

Example 2:

Python3




byte_val = b'\x00\x10'
 
int_val = int.from_bytes(byte_val, "little")
 
# printing int object
print(int_val)

Output:

4096

Example 3:

Python3




byte_val = b'\xfc\x00'
 
# 2's complement is enabled in big
# endian byte order format
int_val = int.from_bytes(byte_val, "big", signed="True")
 
# printing int object
print(int_val)

Output:

-1024

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!