[XviD-devel] Re: log2 hacking...

Felix von Leitner xvid-devel@xvid.org
Sun, 19 Jan 2003 04:57:21 +0100


Thus spake Christoph Lampert (chl@math.uni-bonn.de):
> I'm need a quick way to calculate the next higher (or equal) power
> of two than a given value X:

> So for X=320 is should be 512 and for X=720 it should be 1024. For X=1024
> it should be 1024 as well, etc. 
> I also need the log2() of this value, so the routine should be something
> like 

> {
>  exponent = log2(X);
>  value = 1<< exponent; 
> }

That looks like you really don't want the exponent, but you want all
non-leading ones to be set to zero.

If that is the case, this routine is for you (for up to 32-bit values):

  int onlyfirstbit(int x) {
    x |= (x >> 1);
    x |= (x >> 2);
    x |= (x >> 4);
    x |= (x >> 8);
    x |= (x >> 16);
    return (x & ~(x >> 1));
  }

clean, portable, and without jumps.

Felix