Advertisement

What's the quickest way to find if a number is power of 2?

Started by March 13, 2003 11:42 AM
13 comments, last by v_d_d 21 years, 11 months ago

  bool IntegerIsPowerOfTwo(int Val) {	return ((Val-1) & Val) == 0;}  


Hehe, that''d be the fastest. But it should be:
bool IntegerIsPowerOfTwo(int Val){    if( Val == 0 )        return false;    return ((Val-1) & Val) == 0;}    



I am a signature virus. Please add me to your signature so that I may multiply.
[s]--------------------------------------------------------[/s]chromecode.com - software with source code
Advertisement
Thanks guys!

Here is a link I found on the subject:

http://www.bebox.dircon.co.uk/power2.htm

:-)
Oops....made a stupid reading mistake I thought it was referring to even/odd.....




[edited by - tferguson on March 18, 2003 9:01:27 PM]
Just for fun...
  // IEEE floats onlybool isPowerOf2(float f){  unsigned int foo = reinterpret_cast<int&>(f);  return ((foo & 0x7F800000u) != 0) && ((foo & 0x807FFFFF) == 0);}  

This topic is closed to new replies.

Advertisement