C/C++ Function to Compute the Next Highest Power of 2 for a 32-bit Integer


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:

1
2
3
4
5
6
7
8
9
#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; })
#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.

1
2
3
4
5
6
7
8
9
10
11
12
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;
}
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) —

GD Star Rating
loading...
201 words
Last Post: Teaching Kids Programming - Implement the Counter method in Python
Next Post: Teaching Kids Programming - Greatest Common Divisor of Strings

The Permanent URL is: C/C++ Function to Compute the Next Highest Power of 2 for a 32-bit Integer

Leave a Reply