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

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

    With numpy it is easy like this:

    Bytes = numpy.fromfile(filename, dtype = "uint8")
    Bits = numpy.unpackbits(Bytes)
    

    More info here:
    http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html

    0 讨论(0)
  • 2020-12-05 07:21

    Read the bits from a file, low bits first.

    def bits(f):
        bytes = (ord(b) for b in f.read())
        for b in bytes:
            for i in xrange(8):
                yield (b >> i) & 1
    
    for b in bits(open('binary-file.bin', 'r')):
        print b
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题