Skip to content

Instantly share code, notes, and snippets.

@tadasv
Created February 3, 2014 02:38
Show Gist options
  • Save tadasv/8778121 to your computer and use it in GitHub Desktop.
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 :)
#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