cc [ flags ] -I/usr/local/include file(s) -L/usr/local/lib -lmcw [ ... ] #include <mathcw.h> extern int nlz (unsigned int); extern int lnlz (unsigned long int); extern int llnlz (unsigned long long int);
DESCRIPTION
Compute the number of leading zero bits in the integer argument. On most systems, the fast algorithm used allows this to be done in a time that is fixed, rather than proportional to the number of bits in a word. The values nlz(u) for u taken from a uniform distribution of random unsigned integers have an exponential distribution: the function value is 0 with probability 1/2 (the bits of u are 1xxx...), is 1 with probability 1/4 (u is 01xxx...), is 2 with probability 1/8 (u is 001xxx...), and so on. The probability of having n leading zero bits in a random integer is thus 2**(-(n+1)).
USEFUL IDENTITIES
ceil(log2(n)) = wordsize - nlz(n - 1) floor(log2(n)) = wordsize - 1 - nlz(n)
The book
describes several implementations of these functions, and is a general treasure trove of clever tricks with integer arithmetic.Henry S. Warren, Jr. Hacker's Delight Addison-Wesley (2003) ISBN 0-201-91465-4