How to Convert bytes to int in Python

To convert bytes to int in Python, you can “use the int.from_bytes() method.” It 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)

Parameters

  1. bytes: It is a byte object.
  2. 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.
  3. 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 1: How to Use int.from_bytes() Method

# 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

Example 2: 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

Example 3: Passing signed=True

The int.from_bytes() method also accepts the signed argument. By default, its value is False.

# 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

That’s it.

Leave a Comment

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