Skip to main content
Python-Convert-Bytes-to-INT

Python bytes to int

This python 3 tutorial help to convert bytes to an integer. Python 3.2 has introduced a function int.from_bytes(), that helps to convert bytes to an integer. It returns immutable bytes object initialized with the given size and data. The bytes() is a built-in method that use to create bytes.

Python bytes to int

Let’s convert bytes to int into python using int.from_bytes() method. A byte value can be interchanged to an int value using the int.from_bytes() function. It returns the integer represented of the given array of bytes.

The syntax

int.from_bytes(bytes, byteorder, *, signed=False)

Where parameters are:

  • bytes: This is a byte object.
  • byteorder: It help to determines the order of representation of the integer value. .
  • signed: The default value is False. It indicates whether two’s complement is used to represent the integer..

Python Code to Convert Bytes to INT

# Declaring byte value
byte_val = b'\x03\x45'

# Converting bytes to int
int_val = int.from_bytes(byte_val, "big")

# print output
print(int_val)

The output:

837

Convert Bytes to INT by byteorder = “little”

Let’s pass byteorder = “little” into int.from_bytes() method:

# Declaring byte value
byte_val = b'\x03\x45'

# Converting bytes to int
int_val = int.from_bytes(byte_val, "little")

# print output
print(int_val)

Output:
17667

Convert Bytes to INT by Passing signed=True

The int.from_bytes() method also accepts the signed argument. its default value is False. We’ll pass signed = True into this method.

# Declaring byte value
byte_val = b'\xcd\x45'

# Converting bytes to int
int_val = int.from_bytes(byte_val, "big", signed=True)

# print output
print(int_val)

Output:
-12987

Leave a Reply

Your email address will not be published. Required fields are marked *