This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

| Next Power Of 2 Submitted by

Here is my little code of the day tip thing, its used to replace all those large and bulky NextPow2 functions that people always seem to use. Its simple and effective and it works, well on Intel based systems anyways - I'm sure that it could be adapted to the motorolla and other chips.
What it does is it uses intel's Bit Scan Reverse function to scan the integer from the highiest bit to the lowest bit that is a '1'. Then it puts the location of that bit into the ecx value, that is increased by one so it will get the next highiest value, and finally the return value is shifted by the ecx register to return the next highiest power of two.
Dominik Grabiec
(a.k.a Dæmin)
sdgrab@eisa.net.au

Download Associated File: nextpow2.cpp (305 bytes)

    //Editor's note:
    //COTD Entry:  Next Power Of 2 by Dominik Grabiec [sdgrab@eisa.net.au]

    __inline int NextPow2(int Number)
    {
        unsigned int RetVal = 1;
        __asm
        {
            xor ecx, ecx
            bsr ecx, Number
            inc ecx
            shl RetVal, cl
        }
        return(RetVal);
    }

The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.