Jump to content
  • Advertisement
Sign in to follow this  
littlekid

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

This topic is 2567 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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


Link to post
Share on other sites
Advertisement
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

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.



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
x86 has instructions called bsr and bsf that could make this pretty easy.unsigned long mask = your input value;
unsigned long bitIndex = 0;
_BitScanReverse(&bitIndex, mask);
return bitIndex;

Share this post


Link to post
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??


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
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!