Skip to content

Instantly share code, notes, and snippets.

@k06a
Created August 18, 2013 12:44
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 k06a/6261475 to your computer and use it in GitHub Desktop.
Save k06a/6261475 to your computer and use it in GitHub Desktop.
Fast log2 by reversing and then counting trailing bits - see run result at http://codepad.org/MQeUVaiK
// Copyright 2013 (c) Anton Bukov - https://github.com/k06a
// Inspired by http://graphics.stanford.edu/~seander/bithacks.html
#define P0(a) (a)
#define P1(a) (((P0(a) & 0x55555555) << 1) | ((P0(a) & 0xAAAAAAAA) >> 1))
#define P2(a) (((P1(a) & 0x33333333) << 2) | ((P1(a) & 0xCCCCCCCC) >> 2))
#define P3(a) (((P2(a) & 0x0F0F0F0F) << 4) | ((P2(a) & 0xF0F0F0F0) >> 4))
#define P4(a) (((P3(a) & 0x00FF00FF) << 8) | ((P3(a) & 0xFF00FF00) >> 8))
#define P5(a) (((P4(a) & 0x0000FFFF) << 16) | ((P4(a) & 0xFFFF0000) >> 16))
int log2(int n)
{
union { float f; unsigned i; } fi = { (float)(P5(n) & -P5(n)) };
return 31 - ((fi.i >> 23) - 0x7f);
}
void main()
{
printf("%i", log2(3000000)); // 21
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment