AppDividend
Latest Code Tutorials

How to Convert Python bytes to int

0

Python 3.2 now has a function called int.from_bytes() to convert bytes to an integer. To create bytes in Python, use the bytes() method. The bytes() is a built-in method that returns immutable bytes object initialized with the given size and data.

Python bytes to int

To convert bytes to int in Python, use the int.from_bytes() method. A byte value can be interchanged to an int value using the int.from_bytes() function.

The int.from_bytes() function 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 of “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 byteorder is “little“, the most significant byte is at the beginning of the byte array.

Passing byteorder = “little”

If 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 your answer you are looking for, and That is it for converting bytes to integer in Python tutorial.

 

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.