Skip to content

Instantly share code, notes, and snippets.

@Yi-Tseng
Created February 21, 2017 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yi-Tseng/c54c8f2f47c2eb62adf1a9c15a7acf12 to your computer and use it in GitHub Desktop.
Save Yi-Tseng/c54c8f2f47c2eb62adf1a9c15a7acf12 to your computer and use it in GitHub Desktop.
#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;
}
@Yi-Tseng
Copy link
Author

Expected result:

ffffffff 0
7fffffff 1
3fffffff 2
1fffffff 3
0fffffff 4
07ffffff 5
03ffffff 6
01ffffff 7
00ffffff 8
007fffff 9
003fffff 10
001fffff 11
000fffff 12
0007ffff 13
0003ffff 14
0001ffff 15
0000ffff 16
00007fff 17
00003fff 18
00001fff 19
00000fff 20
000007ff 21
000003ff 22
000001ff 23
000000ff 24
0000007f 25
0000003f 26
0000001f 27
0000000f 28
00000007 29
00000003 30
00000001 31
00000000 32

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment