Created
February 21, 2017 00:49
-
-
Save Yi-Tseng/c54c8f2f47c2eb62adf1a9c15a7acf12 to your computer and use it in GitHub Desktop.
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<stdio.h> | |
#include<stdlib.h> | |
uint8_t clz(uint32_t test, uint8_t bits) { | |
uint32_t cut = (test >> (32 - bits)) << (32 - bits); | |
if (cut == 0) { | |
return bits; | |
} | |
if (bits == 0) { | |
return 0; | |
} | |
uint8_t half = bits/2; | |
uint8_t result = clz(cut, half); | |
if (result == half) { | |
return half + clz(cut << half, half); | |
} else { | |
return result; | |
} | |
} | |
int main() { | |
int c; | |
uint32_t a = 0xffffffff; | |
for (c=0; c<32; c++) { | |
printf("%08x %u\n", a, clz(a, 32)); | |
a = a >> 1; | |
} | |
printf("%08x %u\n", a, clz(a, 32)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Expected result: