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;
Fri, Mar 5, 2010
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;
Leave a Reply
You must be logged in to post a comment.