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

3

19

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
Pacifistic answered 10/7, 2017 at 11:19 Comment(0)
P
22

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'
Prelacy answered 10/7, 2017 at 11:32 Comment(4)
I tried finding the bit representation of a UUID using this method. When i used len function on that bit string, it came out to be 127. But UUID's are 128 bit numbers. Can you please explain why the length calculated was 127?Lynettelynn
0-127 is 128 numbersInerney
if the bytes has leading zeros, this method does not work.Paphlagonia
To achieve reverse operation is INTEGER.to_bytes(..)Quilmes
D
11

Iterating over a bytes object gives you 8 bit ints which you can easily format to output in binary representation:

import numpy as np

>>> my_bytes = np.random.bytes(10)
>>> my_bytes
b'_\xd9\xe97\xed\x06\xa82\xe7\xbf'

>>> type(my_bytes)
bytes

>>> my_bytes[0]
95

>>> type(my_bytes[0])
int

>>> for my_byte in my_bytes:
>>>     print(f'{my_byte:0>8b}', end=' ')

01011111 11011001 11101001 00110111 11101101 00000110 10101000 00110010 11100111 10111111

A function for a hex string representation is builtin:

>>> my_bytes.hex(sep=' ')
'5f d9 e9 37 ed 06 a8 32 e7 bf'
Dagoba answered 22/9, 2020 at 23:28 Comment(0)
U
0

Use bitstring package

import bitstring
bitstring.BitArray(b"\x5a\x01\x00").bin

Returns '010110100000000100000000'

Warning

The accepted answer bin(int.from_bytes(b"\x5a\x01\x00", byteorder=sys.byteorder)) returns '0b101011010' which is obviously nonsense!

The accepted answer might fail if you convert int.from_bytes(b'\x11\x00', byteorder=sys.byteorder). It might be also contraintuitive to represent bytes in little endian int, when it swap the bytes order and I don't know what's going on under the hood when dealing with e.g. sequence of 9 bytes.

Uptotheminute answered 1/5 at 21:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.