Using Python How can I read the bits in a byte?

前端 未结 9 545
礼貌的吻别
礼貌的吻别 2020-12-05 06:55

I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var = fread(file, 8, \'ubit1\'), and then retrie

9条回答
  •  无人及你
    2020-12-05 07:13

    You won't be able to read each bit one by one - you have to read it byte by byte. You can easily extract the bits out, though:

    f = open("myfile", 'rb')
    # read one byte
    byte = f.read(1)
    # convert the byte to an integer representation
    byte = ord(byte)
    # now convert to string of 1s and 0s
    byte = bin(byte)[2:].rjust(8, '0')
    # now byte contains a string with 0s and 1s
    for bit in byte:
        print bit
    

提交回复
热议问题