count_leading_zeros

mdcraft.lib.bit.count_leading_zeros(x: int | int_t, bits: int | int_t) int[source]

Counts the number of leading zeros in the binary representation of an integer.

Parameters:
xint

An integer to count leading zeros in.

bitsint

The number of bits in the binary representation.

Returns:
nlzint

The number of leading zeros in the binary representation of x. If x is zero, bits is returned.

Examples

>>> n = 1
>>> f"{n:0>32b}"
'00000000000000000000000000000001'
>>> count_leading_zeros(n, 32)
31
>>> n = 2 ** 63 - 1
>>> f"{n:0>64b}"
'0111111111111111111111111111111111111111111111111111111111111111'
>>> count_leading_zeros(n, 64)
1