Created
February 3, 2014 02:38
-
-
Save tadasv/8778121 to your computer and use it in GitHub Desktop.
A way to count leading 0 bits of a 32 bit int in 5 instructions :)
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> | |
/* | |
You can do the same with a built in function if your compiler supports it: | |
zeros = __builtin_clz(arg); | |
*/ | |
int main(int argc, const char *argv[]) | |
{ | |
// number for which you want to count leading zeros | |
unsigned int arg = 2147483648; | |
unsigned int result; | |
asm ("bsr %0, %%eax\n" | |
"movl $63, %%ecx\n" | |
"cmovz %%ecx, %%eax\n" | |
"xor $31, %%eax\n" | |
"movl %%eax, %1\n" | |
: "=r" (result) | |
: "r" (arg) | |
: "%eax", "%ecx"); | |
printf("zeros: %d\n", result); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment