pythonnumpybinarybitboard

Bit scan forward and reverse in numpy


I need to count the number of trailing and leading zeros in a numpy uint64 variable, so right now I'm doing it like this:

# n > 0
n = np.uint64(100)
s = np.binary_repr(n)
trail_zeros = len(s) - len(s.rstrip('0'))
lead_zeros = 64 - len(s)

Is there a better way of doing this, without using strings? The priority is speed. Thank you!


Solution

  • For numbers in [0,2**63), we can use some arithmetic operations to get the leading and trailing zeros in their binary formats and hence skip the string manipulations -

    def get_leading_trailing_zeros(n):
        a = (2**np.arange(64) & n)
        lead_zeros = 64-a.argmax()-1
        if n==0:
            trail_zeros = 1
        else:
            trail_zeros = (a==0).argmin()
        return lead_zeros,trail_zeros