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:
'\xbe\x00\xc8d\xf8d\x08\xe4.\x07~\x03\x9e\x07\xbe\x03\xde\x07\xfe\n'
I am having a hard time manipulating this data. If I try and print each line, python freezes, and emits beeping noises (I think there's a binary beep code in there somewhere). How do I go about using this data safely? How can I convert each hex number to decimal?
In Python, the simple way to get this number is using the built in bin() function (note - this returns a binary string, not the binary bits), and using int() to convert back from binary to a base 10 integer.
To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing. Unlike text files, binary files are not human-readable. When opened using any text editor, the data is unrecognizable.
Python has tools for working with binary files. Binary files use strings of type bytes. This means when reading binary data from a file, an object of type bytes is returned. The binary file is opened using the open() function, whose mode parameter contains the character 'b'.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With