Page 1 of 1

C\C++: Get highest bit '1' in unsigned int.

Posted: Sun Oct 12, 2008 12:20 am
by The Coolest

Code: Select all

int GetHighestBit(DWORD_PTR _dwValue)
{
	if (!_dwValue)
		return -1;

	DWORD_PTR dwpCnt;	
	int iRet;

#ifdef _WIN64
	dwpCnt = 0x8000000000000000;
	iRet = 63;
#else
	dwpCnt = 0x80000000;
	iRet = 31;
#endif

	while (!(dwpCnt & _dwValue))
	{
		iRet--;
		dwpCnt = dwpCnt >> 1;
	}

	return iRet;
}
This is what I have right now, any idea how to improve this code? Speed is of no importance since it only executes once in the program.
The solution must not include any extra libraries, since I'm trying to keep the executable small.

Posted: Sun Oct 12, 2008 6:55 pm
by hathor

Code: Select all

/** Returns the most significant bit set in a value.
        */
        static FORCEINLINE unsigned int mostSignificantBitSet(unsigned int value)
        {
            unsigned int result = 0;
            while (value != 0) {
                ++result;
                value >>= 1;
            }
            return result-1;
        }

Posted: Sun Oct 12, 2008 10:30 pm
by The Coolest
O damn, looks like I've been looking at it from the wrong angle. :oops:

Thanks :D

Code: Select all

int GetHighestBit(DWORD_PTR _dwValue)
{
	int iRet = 0;

	while (_dwValue)
	{
		iRet++;
		_dwValue >>= 1;
	}

	return --iRet;
}