In python, long integers have an unlimited range. Is there a simple way to convert a binary file (e.g., a photo) into a 开发者_StackOverflowsingle long integer?
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.
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.
精彩评论