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

前端 未结 9 538
礼貌的吻别
礼貌的吻别 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:07

    To read a byte from a file: bytestring = open(filename, 'rb').read(1). Note: the file is opened in the binary mode.

    To get bits, convert the bytestring into an integer: byte = bytestring[0] (Python 3) or byte = ord(bytestring[0]) (Python 2) and extract the desired bit: (byte >> i) & 1:

    >>> for i in range(8): (b'a'[0] >> i) & 1
    ... 
    1
    0
    0
    0
    0
    1
    1
    0
    >>> bin(b'a'[0])
    '0b1100001'
    

提交回复
热议问题