Round up to the next highest power of 2

version1

1
2
3
4
5
6
static unsigned int power2gt(unsigned int size) {
while (1) {
if (i >= size) return i;
i *= 2;
}
}

version2

1
2
3
4
5
6
7
8
9
static unsigned int power2gt(unsigned int size) {
--size;
size |= size >> 1;
size |= size >> 2;
size |= size >> 4;
size |= size >> 8;
size |= size >> 16;
return size + 1;
}

参考资料

  1. the explanation of version2:here
  2. Reidis#issue4776