The byte is a variable or object type used to store single or multiple bytes in a single variable. Bytes are mainly related to numbers like integers. Bytes can be converted into the integer or int by using the int.from_bytes()
method. During the conversion, the MSB or LSB is important for the resulting integer. In this tutorial, we examine different ways to convert bytes into an int.
Convert Byte To Int
In this part, we convert bytes into the int or integer by using the int.from_bytes()
method. This method accepts two or three parameters where the first parameter is the bytes to convert. The second parameter is the byte order which is MSB as right
in the following example.
bytes = b'\x00\x01'
i = int.from_bytes(bytes,"big")
print(i)
1
Convert Byte To Int MSB As Left
While converting bytes into int the conversion direction is important we can specify the conversion direction by providing the MSB
or LSB
type. In the following example, we set the MSB as little
.
bytes = b'\x00\x01'
i = int.from_bytes(bytes,"little")
print(i)
Convert Byte To Int As Signed
By default, the provided bytes are converted as unsigned. But we can make the conversion as signed
by setting the signed
parameter as True
.
bytes = b'\x00\x01'
i = int.from_bytes(bytes,signed="True")
print(i)