views:

67

answers:

2

In python, long integers have an unlimited range. Is there a simple way to convert a binary file (e.g., a photo) into a single long integer?

+3  A: 

Here's one way to do it.

def file_to_number(f):
    number = 0
    for line in f:
        for char in line:
            number = ord(char) | (number << 8)
    return number

You might get a MemoryError eventually.

Aaron Gallagher
As it's a binary file I'm not sure it makes sense to iterate over lines (I'm not sure it's harmful either, but a line just isn't meaningful in this case).
Scott Griffiths
Sure; it's just the simplest way to semi-lazily read data out of a file. If there was a `for chunk in f.read_chunks(4096):` or so, I would've used that.
Aaron Gallagher
+3  A: 

Using the bitstring module it's just:

bitstring.BitString(filename='your_file').uint

If you prefer you can get a signed integer using the int property.

Internally this is using struct.unpack to convert chunks of bytes, which is more efficient than doing it per byte.

Scott Griffiths