# How to get the exponent of a power of 2 value?

## Recommended Posts

Hi, suppose my value is always in power of 2 e.g 512, 1024, 32, 64.

Is there any quick way of getting the exponent of it? for e.g 256 would yield an exponent of 8.

Hence given the value 256, what quick fast way can I get the exponent value 8?

I was thinking of looping the bits and then finding which bit position is set. Is that the best way to go about doing it?

regards

##### Share on other sites
Are you using java? if so i know it has a getExponenent method in its math library.

Example System.out.println(Math.getExponent(2)); would return 1

if your using another language i'm sure they should have similar methods available.

##### Share on other sites
Use log function :
[code]
int powerOfTwo(unsigned exponent){
return std::ceil( std::log(exponent) / std::log(2) );
}
[/code]

##### Share on other sites
Alternately you can use a [url=http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious]logarithm bit hack[/url].

##### Share on other sites
[quote name='Dr1fter' timestamp='1305467263' post='4811071']
Are you using java? if so i know it has a getExponenent method in its math library.

Example System.out.println(Math.getExponent(2)); would return 1

if your using another language i'm sure they should have similar methods available.
[/quote]

ah sorry, i didn't mentioned, I am using C++. I am not sure what functions in C++ can i use, other than maybe log??

regards

##### Share on other sites
x86 has instructions called [url="http://msdn.microsoft.com/en-us/library/fbxyd7zd(v=vs.80).aspx"]bsr[/url] and [url="http://msdn.microsoft.com/en-us/library/wfd9z0bb(v=vs.80).aspx"]bsf[/url] that could make this pretty easy.[code]unsigned long mask = your input value;
unsigned long bitIndex = 0;
return bitIndex;[/code]

##### Share on other sites
Is it better to use the builtin functions as specified by Hodgman or would it be better to just use the log hacks offered by Sicrane? I was just wondering if does using any have a slight benefit over the other??

[code]
For Hodgman solution this is what i did:
size_t GetPowerTwoExponent(size_t value)
{
#if defined(MSVC_COMPILER)
size_t index = 0;
_BitScanForward(&index, value);
return index;
#elif defined(GCC_COMPILER) || defined(CLANG_COMPILER)
return __builtin_ctz(value);
#endif
}
[/code]

##### Share on other sites
Consider using a clear and portable solution and worry about optimization later?

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628290
• Total Posts
2981858

• 11
• 10
• 10
• 11
• 17