Skip to content

Instantly share code, notes, and snippets.

@farrrb
Created March 9, 2018 17:05
Show Gist options
  • Save farrrb/3ccc5b4b0aace1c5f6ba7f4945bf17d0 to your computer and use it in GitHub Desktop.
Save farrrb/3ccc5b4b0aace1c5f6ba7f4945bf17d0 to your computer and use it in GitHub Desktop.
Fast and efficient log2 function with gcc builtin
#include <stdio.h>
#include <stdint.h>
// log 2 - with ceil rounding
int32_t log2_uint32 (uint32_t u)
{
if (u == 0) { return INT32_MIN; }
return ((int32_t)31 - (int32_t)__builtin_clz(u));
}
int main(int argc, char *argv[])
{
printf("\n%d", log2_uint32(0x0));
printf("\n%d", log2_uint32(0x1));
printf("\n%d", log2_uint32(0x2));
printf("\n%d", log2_uint32(0x3));
printf("\n%d", log2_uint32(0x4));
printf("\n%d", log2_uint32(0x10));
printf("\n%d", log2_uint32(0x20));
printf("\n%d", log2_uint32(0x40));
printf("\n%d", log2_uint32(0x80));
printf("\n%d", log2_uint32(7000));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment