Game Development Community

dev|Pro Game Development Curriculum

Next Power of Two

by Dominik Grabiec · 02/09/2001 (11:30 pm) · 3 comments

This function is 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.

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

#1
10/05/2001 (2:34 am)
This function doesn't trap the situation where the input number is already a pure power of two.

Aligning a 256 byte structure upon a 512 byte boundary is somewhat wasteful, yes?
#2
06/19/2006 (4:45 pm)
Don't forget that the latest VC compilers (i think since 7.0, definitely 7.1 though) already have a _BitScanReverse intrinsic, cutting out the need for inline asm (and helping the optimiser at the same time). Other compilers such as GCC probably implement similar intrinsics.

#include
#pragma intrinsic(_BitScanReverse)

__inline unsigned long NextPow2(unsigned int number)
{
unsigned long tmp = 0;
_BitScanReverse(&tmp,number);
return 1< }
#3
01/23/2010 (11:52 pm)
Okay, this originally was an entry on Flipcode way back in the day (2001 it would seem), and I was doing a lot of assembler hacking back then.

For code these days this has a lot of negatives, as we should be coding for 64 bit now, don't need to use that much assembly, and optimising algorithms rather than turning functions into assembly will give you the biggest benefit.