Original: http://groups.google.co.uk/group/comp.lang.c/browse_thread/thread/27bec95613efeed6/6a5983535088d349?q=0x7dcd629#6a5983535088d349

const char clz_table[32] =
  {
    0, 31, 9, 30, 3, 8, 18, 29, 2, 5, 7, 14, 12, 17,
    22, 28, 1, 10, 4, 19, 6, 15, 13, 23, 11, 20, 16,
    24, 21, 25, 26, 27
  };
unsigned long clz(unsigned long n)
  {
    unsigned long c = 0x7dcd629;       /* magic constant… */

    n |= (n >> 1);
    n |= (n >> 2);
    n |= (n >> 4);
    n |= (n >> 8);
    n |= (n >> 16);
    if (n == 0) return 32;
    n = c + (c * n);
    return 31 – clz_table[n >> 27];       /* For little endian    */
  }

Advertisements