Home > OS >  Python - Fastest way to strip the trailing zeros from the bit representation of a number
Python - Fastest way to strip the trailing zeros from the bit representation of a number

Time:03-22

This is the python version of Results on my system

CodePudding user response:

while (num & 0xffffffff) == 0:
    num >>= 32
if (num & 0xffff) == 0:
    num >>= 16
if (num & 0xff) == 0:
    num >>= 8
if (num & 0xf) == 0:
    num >>= 4
if (num & 0x3) == 0:
    num >>= 2
if (num & 0x1) == 0:
    num >>= 1

The idea here is to perform as few shifts as possible. The initial while loop handles numbers that are over 32 bits long, which I consider unlikely but it has to be provided for completeness. After that each statement shifts half as many bits; if you can't shift by 16, then the most you could shift is 15 which is (8 4 2 1). All possible cases are covered by those 5 if statements.

  • Related