Утилитный функции по работе с числами степени двойки
Автор: Pavel Tumik
Несколько утилитных функций для работы с числами степени двойки:
inline bool isPowerOf2(unsigned x) { if ( x<1) return false; return ( x&( x-1))==0; } // Returns the least power of 2 greater than or equal to "x". // Note that for x=0 and for x>2147483648 this returns 0! __declspec( naked) unsigned __fastcall ceilPowerOf2( unsigned x) { __asm { xor eax,eax dec ecx bsr ecx,ecx cmovz ecx,eax setnz al inc eax shl eax,cl ret } } // Returns the greatest power of 2 less than or equal to "x". // Note that for x=0 this returns 0! __declspec( naked) unsigned __fastcall floorPowerOf2( unsigned x) { __asm { xor eax,eax bsr ecx,ecx setnz al shl eax,cl ret } }
9 июня 2009