Convert a 64 bit integer into 8 separate 1 byte integers in python

后端 未结 5 1337
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 12:20

In python, I have been given a 64 bit integer. This Integer was created by taking several different 8 bit integers and mashing them together into one giant 64 bit integer.

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-20 12:57

    Here's a version using struct:

    import struct
    n = 2592701575664680400
    bytes = struct.unpack('8B', struct.pack('Q', n))
    

    The bytes are returned in the opposite order that you showed in your question.

    Here are the performance stats:

    python -m timeit -s "import struct" "struct.unpack('8B', struct.pack('Q', 2592701575664680400))"
    1000000 loops, best of 3: 0.33 usec per loop
    

    On my computer, this is three times faster than the byte-shifting solution.

提交回复
热议问题