Search code examples
pythonpython-3.xtype-conversionbytebytestream

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


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

Solution

  • 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'