Re: C macro to find the next power of 2 ?

From: Luigi Rizzo <rizzo_at_icir.org>
Date: Wed, 7 Feb 2007 02:49:18 -0800
On Wed, Feb 07, 2007 at 11:25:49AM +0100, Stefan Bethke wrote:
> On Wed, February 7, 2007 09:41, Luigi Rizzo wrote:
> > 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.
> 
> _Hacker's Delight_ contains many cool tricks, including multiple solutions
> for this, IIRC.  I'll have a look tonight when I'm back home.

funny it looks like the same code that i posted,
except that mine is functional and theirs procedural:

my version:

        #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)

Hacker's Delight version

	unsigned clp2(unsigned x) {
	   x = x - 1;
	   x = x | (x >> 1);
	   x = x | (x >> 2);
	   x = x | (x >> 4);
	   x = x | (x >> 8);
	   x = x | (x >>16);
	   return x + 1;
	}

thanks for the pointer.

	luigi

> 
> Cheers,
> Stefan
> 
> -- 
> Stefan Bethke <stb_at_lassitu.de> +49 170 3460140
> 
> _______________________________________________
> freebsd-current_at_freebsd.org mailing list
> http://lists.freebsd.org/mailman/listinfo/freebsd-current
> To unsubscribe, send any mail to "freebsd-current-unsubscribe_at_freebsd.org"
Received on Wed Feb 07 2007 - 09:49:48 UTC

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