---
# System prepended metadata

title: Round up to the next highest power of 2
tags: [bitwise, learning]

---

###### tags: `learning` `bitwise`

# Round up to the next highest power of 2

ref = 
http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2

```cpp=
unsigned int v; // compute the next highest power of 2 of 32-bit v

v--;

v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;

v++;
```
in the edge case where v is 0, it returns 0, which isn't a power of 2; you might append the expression v += (v == 0) to remedy this if it matters.
