Searching/reading binary data in Python

前端 未结 8 1843
情歌与酒
情歌与酒 2020-12-25 12:15

I\'m reading in a binary file (a jpg in this case), and need to find some values in that file. For those interested, the binary file is a jpg and I\'m attempting to pick out

8条回答
  •  天涯浪人
    2020-12-25 12:53

    The bitstring module was designed for pretty much this purpose. For your case the following code (which I haven't tested) should help illustrate:

    from bitstring import ConstBitStream
    # Can initialise from files, bytes, etc.
    s = ConstBitStream(filename='your_file')
    # Search to Start of Frame 0 code on byte boundary
    found = s.find('0xffc0', bytealigned=True)
    if found:
        print("Found start code at byte offset %d." % found[0])
        s0f0, length, bitdepth, height, width = s.readlist('hex:16, uint:16, 
                                                            uint:8, 2*uint:16')
        print("Width %d, Height %d" % (width, height))
    

提交回复
热议问题