C macro to find the next power of 2 ?

From: Luigi Rizzo <rizzo_at_icir.org>
Date: Wed, 7 Feb 2007 00:41:31 -0800
This is any good as any of our lists to ask, but since it
came up while looking at device drivers, i thoght
that maybe someone has an answer here...

My problem is that some hardware wants data structures aligned to
the next power of 2 with respect to their size, and the code
in question (the ehci driver in case you care) has hardwired
constants for this, and possibly wrong ones.

It would be nice if one could write

	struct foo_desc {
		...
	};

	#define FOO_ALIGN next_power_of_2(sizeof(struct foo_desc))

instead of having to count fields and make guesses on the size
of pointers and so on.

One way i have come up with is the following:

	#define b2(x)   (   (x) | (   (x) >> 1) )
	#define b4(x)   ( b2(x) | ( b2(x) >> 2) )
	#define b8(x)   ( b4(x) | ( b4(x) >> 4) )
	#define b16(x)  ( b8(x) | ( b8(x) >> 8) )
	#define b32(x)  (b16(x) | (b16(x) >>16) )
	#define next_power_of_2(x)      (b32(x-1) + 1)

Basically if i is the first bit set in x, macro b2 makes sure
that 2 bits (i and i-1) are set, macro b4..b32 do the same
for up to 32 bits. The offsets -1 in the call to b32()
are just to handle the case when x is already a power of 2,
and the final +1 produces the result.

But i was wondering if there is some simpler code which
can still be computed as a compile-time constant ?

	cheers
	luigi
Received on Wed Feb 07 2007 - 07:41:40 UTC

This archive was generated by hypermail 2.4.0 : Wed May 19 2021 - 11:39:05 UTC