Given a 32-bit integer, we want to find out the next highest power of 2. For example, the next power of two for 127 is 128. We can use the following C Macro:
#define next_power_of_two(x) \
({ unsigned int vv = x; \
vv--; \
vv |= vv >> 1; \
vv |= vv >> 2; \
vv |= vv >> 4; \
vv |= vv >> 8; \
vv |= vv >> 16; \
++vv; })
We can also use the following C/C++ function to compute the next power of two. If the given integer it is already the power of two, it will simply return it.
inline unsigned int
next_power_of_two(int x) {
unsigned int v = x;
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
++v;
return v;
}
–EOF (The Ultimate Computing & Technology Blog) —
184 wordsLast Post: Teaching Kids Programming - Implement the Counter method in Python
Next Post: Teaching Kids Programming - Greatest Common Divisor of Strings