Search code examples
pythonbinarybytebitconverters

How can I convert from bytes to binary numbers in Python?


So I'm a total Python beginner and I got this byte object:

byte_obj = b'\x45\x10\x00\x4c\xcc\xde\x40\x00\x40\x06\x6c\x80\xc0\xa8\xd9\x17\x8d\x54\xda\x28'

But I have no idea how to put this in a binary number, I only know it's gonna have 32 bits.


Solution

  • You could try int.from_bytes(...), documented here e.g.:

    >>> byte_obj = b'\x45\x10\x00\x4c\xcc\xde\x40\x00\x40\x06\x6c\x80\xc0\xa8\xd9\x17\x8d\x54\xda\x28'
    
    >>> int.from_bytes(byte_obj, byteorder='big')
    394277201243797802270421732363840487422965373480
    

    Where byteorder is used to specify whether the input is big- or little-endian (i.e. most or least significant byte first).

    (Looks a bit bigger than 32 bits though!)