Convert an integer to binary without using the built-in bin function

后端 未结 15 1559
深忆病人
深忆病人 2020-12-07 01:14

This function receives as a parameter an integer and should return a list representing the same value expressed in binary as a list of bits, where the first element in the l

15条回答
  •  天涯浪人
    2020-12-07 01:29

    You can use numpy package and get very fast solution:

    python -m timeit -s "import numpy as np; x=np.array([8], dtype=np.uint8)" "np.unpackbits(x)"
    1000000 loops, best of 3: 0.65 usec per loop
    
    python -m timeit "[int(x) for x in list('{0:0b}'.format(8))]"
    100000 loops, best of 3: 3.68 usec per loop
    

    unpackbits handles inputs of uint8 type only, but you can still use np.view:

    python -m timeit -s "import numpy as np; x=np.array([124567], dtype=np.uint64).view(np.uint8)" "np.unpackbits(x)"
    1000000 loops, best of 3: 0.697 usec per loop
    

提交回复
热议问题