How to Convert Bytes to Int in Python?
Last Updated :
17 Nov, 2022
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
byte_val = b '\x00\x01'
int_val = int .from_bytes(byte_val, "big" )
print (int_val)
|
Output:
1
Example 2:
Python3
byte_val = b '\x00\x10'
int_val = int .from_bytes(byte_val, "little" )
print (int_val)
|
Output:
4096
Example 3:
Python3
byte_val = b '\xfc\x00'
int_val = int .from_bytes(byte_val, "big" , signed = "True" )
print (int_val)
|
Output:
-1024
Share your thoughts in the comments
Please Login to comment...