How can I convert bytes object to decimal or binary representation in python?

KaramJaber picture KaramJaber · Jul 10, 2017 · Viewed 25.5k times · Source

I wanted to convert an object of type bytes to binary representation in python 3.x.

For example, I want to convert the bytes object b'\x11' to the binary representation 00010001 in binary (or 17 in decimal).

I tried this:

print(struct.unpack("h","\x11"))

But I'm getting:

error struct.error: unpack requires a bytes object of length 2

Answer

Oleksii Filonenko picture Oleksii Filonenko · Jul 10, 2017

Starting from Python 3.2, you can use int.from_bytes.

Second argument, byteorder, specifies endianness of your bytestring. It can be either 'big' or 'little'. You can also use sys.byteorder to get your host machine's native byteorder.

import sys
int.from_bytes(b'\x11', byteorder=sys.byteorder)  # => 17
bin(int.from_bytes(b'\x11', byteorder=sys.byteorder))  # => '0b10001'