Convert bytes to int?

ghz 3months ago ⋅ 33 views

I'm currently working on an encryption/decryption program and I need to be able to convert bytes to an integer. I know that:

bytes([3]) = b'\x03'

Yet I cannot find out how to do the inverse. What am I doing terribly wrong?

Answers

To convert bytes back to an integer in Python, you can use the int.from_bytes() method. Here’s how you can do it:

# Convert bytes to integer
byte_value = bytes([3])  # b'\x03'
integer_value = int.from_bytes(byte_value, byteorder='big')  # or 'little'
print(integer_value)  # Output: 3

Explanation

  • bytes([3]) creates a bytes object containing the byte representation of the integer 3.
  • int.from_bytes() takes two arguments:
    • The bytes object you want to convert.
    • The byteorder, which can be either 'big' or 'little'. This specifies the endianness of the byte representation.

Example with multiple bytes

If you have multiple bytes:

byte_value = b'\x01\x02\x03'  # This is equivalent to the integer 66051 in big-endian
integer_value = int.from_bytes(byte_value, byteorder='big')
print(integer_value)  # Output: 66051

You can adjust the byte order according to your needs!