Welcome to little lamb

Code » test-msb » next » tree

[next] / src / m8.c

#include <stdint.h>

typedef uint8_t  u8;
typedef uint32_t u32;
typedef uint64_t u64;

/* de Bruijn magic & table from Jim Mischel */

const u8 table[32] =
{
     0,  9,  1, 10, 13, 21,  2, 29,
    11, 14, 16, 18, 22, 25,  3, 30,
     8, 12, 20, 28, 15, 17, 24,  7,
    19, 27, 23,  6, 26,  5,  4, 31
};

int msb(u64 v)
{
    if (!v) return 0;

    u32 v32;
    u8 n;
    if (v > 0xFFFFFFFF) {
        v32 = v >> 32;
        n = 33;
    } else {
        v32 = v;
        n = 1;
    }

    v32 |= v32 >> 1;
    v32 |= v32 >> 2;
    v32 |= v32 >> 4;
    v32 |= v32 >> 8;
    v32 |= v32 >> 16;

    return n + table[(v32 * 0x07C4ACDDU) >> 27];
}