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

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

    The smallest unit you'll be able to work with is a byte. To work at the bit level you need to use bitwise operators.

    x = 3
    #Check if the 1st bit is set:
    x&1 != 0
    #Returns True
    
    #Check if the 2nd bit is set:
    x&2 != 0
    #Returns True
    
    #Check if the 3rd bit is set:
    x&4 != 0
    #Returns False
    

提交回复
热议问题