开发者

How to convert a binary file into a Long integer?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜