Created
September 13, 2018 14:22
-
-
Save madmann91/83b7c81436893b39b6a8d83d40b4db1c to your computer and use it in GitHub Desktop.
Count leading zeros in a portable manner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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