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

后端 未结 5 1336
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  星月不相逢
    2020-12-20 12:54

    bn = "0010001111111011001000000101100010101010000101101011111000000000"
    
    print([int(bn[i:i+8], 2) for i in range(0,len(bn), 8)])
    [35, 251, 32, 88, 170, 22, 190, 0]
    

    If you are using the binary representation of n then the output would be different:

    n = 2592701575664680373
    bn = bin(n)
    
    print([int(bn[i:i+8], 2) for i in range(0,len(bn), 8)])
    [35, 251, 32, 88, 170, 22, 189, 181]
    

    Some timings:

    In [16]: %%timeit                                                
    numbers = list((n >> i) & 0xFF for i in range(0,64,8))
    list(reversed(numbers))
       ....: 
    100000 loops, best of 3: 2.97 µs per loop
    
    In [17]: timeit [(n >> (i * 8)) & 0xFF for i in range(7, -1, -1)]
    1000000 loops, best of 3: 1.73 µs per loop
    
    In [18]: %%timeit                                                
    bn = bin(n)
    [int(bn[i:i+8], 2) for i in range(0,len(bn), 8)]
       ....: 
    100000 loops, best of 3: 3.96 µs per loop
    

    You can also just divmod:

    out = []
    for _ in range(8):
        n, i = divmod(n, 256)
        out.append(i) 
    out = out[::-1]
    

    Which is almost as efficient:

    In [31]: %%timeit
       ....: n = 2592701575664680411
       ....: out = []
       ....: for _ in range(8):
       ....:     n, i = divmod(n, 1 << 8)
       ....:     out.append(i)
       ....: out[::-1]
       ....: 
    100000 loops, best of 3: 2.35 µs per loop
    

    There is very little advantage in bit shifting with python, I would be more inclined to use whatever you and others find more readable.

提交回复
热议问题