Boost logo

Boost Users :

Subject: Re: [Boost-users] run-time integer log2
From: joel falcou (joel.falcou_at_[hidden])
Date: 2010-07-13 07:04:14


Tim Blechmann wrote:
> hi all,
>
> i am aware, that boost provides a compile-time integer log2 function. but
> what is the best way to compile an integer log2 at run-time?
>
>
In the good'ol Bits Twiddling Hacks page:

unsigned int v; // 32-bit value to find the log2 of
unsigned int r; // result of log2(v) will go here
unsigned int shift;

r = (v > 0xFFFF) << 4; v >>= r;
shift = (v > 0xFF ) << 3; v >>= shift; r |= shift;
shift = (v > 0xF ) << 2; v >>= shift; r |= shift;
shift = (v > 0x3 ) << 1; v >>= shift; r |= shift;
                                        
r |= (v >> 1);

We use a similar stuff in NT². I can be obviously fitted back to 16 and
8 bits integer for more speed.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net