ILOG2 3CW "09 March 2006" "mathcw-1.00"

Table of contents


NAME

ilog2, lilog2, llilog2 - integer part of the base-2 logarithm

SYNOPSIS

cc [ flags ] -I/usr/local/include file(s) -L/usr/local/lib -lmcw [ ... ]

#include <mathcw.h>

extern int ilog2 (unsigned int);

extern int lilog2 (unsigned long int);

extern int llilog2 (unsigned long long int);

DESCRIPTION

Compute the integer part of the base-2 logarithm of 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.


USEFUL IDENTITIES

ilog2(n) = (int)floorl((long double)n)
ilog2(n) = wordsize - 1 - nlz(n)
ilog2(0) = -1

RETURN VALUES

Return the integer part of the base-2 logarithm.

ERRORS

None.

SEE ALSO

clp2(3CW), flp2(3CW), nlz(3CW), ntz(3CW), pop(3CW).

The book

Henry S. Warren, Jr.
Hacker's Delight
Addison-Wesley (2003)
ISBN 0-201-91465-4
describes several implementations of these functions, and is a general treasure trove of clever tricks with integer arithmetic.