Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating binary data in Python

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?

like image 785
Dominic Bou-Samra Avatar asked Jun 17 '10 06:06

Dominic Bou-Samra


People also ask

How do you manipulate binary numbers in Python?

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.

How does Python handle binary files?

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.

Which function is used to fetch binary data from binary file in Python?

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'.


1 Answers

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.

like image 155
ʇsәɹoɈ Avatar answered Oct 10 '22 17:10

ʇsәɹoɈ