开发者

How to convert a binary file into a Long integer?

开发者 https://www.devze.com 2023-01-11 14:01 出处:网络
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:

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

精彩评论

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