Skip to content

Instantly share code, notes, and snippets.

@madmann91
Created September 13, 2018 14:22
Show Gist options
  • Save madmann91/83b7c81436893b39b6a8d83d40b4db1c to your computer and use it in GitHub Desktop.
Save madmann91/83b7c81436893b39b6a8d83d40b4db1c to your computer and use it in GitHub Desktop.
Count leading zeros in a portable manner
#include <iostream>
#include <limits>
#include <algorithm>
#include <cstdint>
int clz(uint32_t u) {
uint32_t a = 0;
uint32_t b = 32;
uint32_t all = 0xFFFFFFFF;
#pragma unroll
for (int i = 0; i < 5; i++) {
auto m = (a + b) / 2;
auto mask = all << m;
if (u & mask) a = m + 1;
else b = m;
}
return 32 - b;
}
bool test() {
for (uint32_t i = 1;
i != std::numeric_limits<uint32_t>::max();
i++) {
if (__builtin_clz(i) != clz(i)) {
std::cout << i << " : " << __builtin_clz(i) << " " << clz(i) << std::endl;
return false;
}
}
return true;
}
int main(int argc, char** argv) {
test();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment