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

Table of contents


NAME

flp2, lflp2, llflp2 - closest power of 2 not greater than argument

SYNOPSIS

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

#include <mathcw.h>

extern unsigned int flp2 (unsigned int);

extern unsigned long int lflp2 (unsigned long int);

extern unsigned long long int llflp2 (unsigned long long int);


DESCRIPTION

Compute the closest power of two not greater than the argument, 2**(floor(log2(arg))). 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, needs only integer operations, and does not require computation of the logarithm and power.

USEFUL IDENTITIES

These identities are valid as long as the intermediate expressions do not overflow and the bit shifts are in [0, wordsize - 1]: clp2(n) = 1 << (wordsize - nlz(n - 1)) clp2(n) = 2 * flp2(n - 1) (n not equal to 1) clp2(n) = flp2(2*n - 1) (n > 0) flp2(2**k * n) = 2**k * flp2(n) flp2(n) = 1 << (wordsize - 1 - nlz(n)) flp2(n) = clp2(n + 1) / 2 (n < 2**(wordsize)) flp2(n) = clp2(n) (if and only if n is 0 or a power of 2) flp2(n) = clp2(n/2 + 1) (n > 0)

RETURN VALUES

Return the closest power of two not greater than the argument.

ERRORS

None.

SEE ALSO

clp2(3CW), ilog2(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.