Manipulating binary data in Python

前端 未结 7 1330
旧时难觅i
旧时难觅i 2021-02-07 07:16

I am opening up a binary file like so:

file = open(\"test/test.x\", \'rb\')

and reading in lines to a list. Each line looks a little like:

7条回答
  •  孤城傲影
    2021-02-07 07:50

    To print it, you can do something like this:

    print repr(data)
    

    For the whole thing as hex:

    print data.encode('hex')
    

    For the decimal value of each byte:

    print ' '.join([str(ord(a)) for a in data])
    

    To unpack binary integers, etc. from the data as if they originally came from a C-style struct, look at the struct module.

提交回复
热议问题