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

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

    Supposing you have a file called bloom_filter.bin which contains an array of bits and you want to read the entire file and use those bits in an array.

    First create the array where the bits will be stored after reading,

    from bitarray import bitarray
    a=bitarray(size)           #same as the number of bits in the file
    

    Open the file, using open or with, anything is fine...I am sticking with open here,

    f=open('bloom_filter.bin','rb')
    

    Now load all the bits into the array 'a' at one shot using,

    f.readinto(a)
    

    'a' is now a bitarray containing all the bits

提交回复
热议问题