Convert bytes to bits in python

后端 未结 9 1638
轮回少年
轮回少年 2020-11-30 07:18

I am working with Python3.2. I need to take a hex stream as an input and parse it at bit-level. So I used

bytes.fromhex(input_str)

to convert t

相关标签:
9条回答
  • 2020-11-30 08:12

    To binary:

    bin(byte)[2:].zfill(8)
    
    0 讨论(0)
  • 2020-11-30 08:12

    Use ord when reading reading bytes:

    byte_binary = bin(ord(f.read(1))) # Add [2:] to remove the "0b" prefix
    

    Or

    Using str.format():

    '{:08b}'.format(ord(f.read(1)))
    
    0 讨论(0)
  • 2020-11-30 08:13

    I think simplest would be use numpy here. For example you can read a file as bytes and then expand it to bits easily like this:

    Bytes = numpy.fromfile(filename, dtype = "uint8")
    Bits = numpy.unpackbits(Bytes)
    
    0 讨论(0)
提交回复
热议问题