RSS

How will you determine if a number is power of 2

Fri, Mar 5, 2010

Algorithm

unsigned int v; // we want to see if v is a power of 2
bool f;         // the result goes here
f = (v & (v – 1)) == 0;
Note that 0 is incorrectly considered a power of 2 here. To remedy this, use:
f = !(v & (v – 1)) && v;

Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Other Posts:

This post was written by:

eXclusiveMinds - who has written 500 posts on eXclusiveMinds.


Contact the author

Leave a Reply

You must be logged in to post a comment.