Sign in to follow this  
littlekid

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

Recommended Posts

littlekid    229
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 this post


Link to post
Share on other sites
Dr1fter    128
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 this post


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

Share this post


Link to post
Share on other sites
littlekid    229
[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 this post


Link to post
Share on other sites
Hodgman    51341
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;
_BitScanReverse(&bitIndex, mask);
return bitIndex;[/code]

Share this post


Link to post
Share on other sites
littlekid    229
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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this