To convert bytes to int in Python, you can use the int.from_bytes() method. This method takes bytes, byteorder, signed, * as parameters and returns the integer represented by the given array of bytes
Syntax
int.from_bytes(bytes, byteorder, *, signed=False)
Arguments
bytes: It is a byte object.
byteorder: It determines the order of representation of the integer value. The byteorder can have values as either “little,” where the most significant bit is stored at the end, or “big”, where MSB is stored at the start and LSB at the end.
signed: It has a False default value. It indicates whether to represent 2’s complement of a number.
Return Value
It returns the integer represented by the given array of bytes.
Example
# Declaring byte value
byte_val = b'\x21\x19'
# Converting to int
int_val = int.from_bytes(byte_val, "big")
# printing int equivalent
print(int_val)
Output
8473
You can see that we passed byteorder = big. The byteorder argument determines the byte order used to represent the integer. If the byteorder is “little“, the most significant byte is at the beginning of the byte array.
Passing byteorder = “little”
If the byteorder is “little“, the most significant byte is at the end of the byte array.
# Declaring byte value
byte_val = b'\x11\x21'
# Converting to int
int_val = int.from_bytes(byte_val, "little")
# printing int equivalent
print(int_val)
Output
8465
Passing signed=True
The int.from_bytes() method also accepts the signed argument. By default, its value is False.
Let’s another example and pass signed = True and see the output.
# Declaring byte value
byte_val = b'\xfc\x00'
# Converting to int
int_val = int.from_bytes(byte_val, "big", signed=True)
# printing int equivalent
print(int_val)
Output
-1024
I hope you found the answer you are looking for, which is for converting bytes to integers in Python.