1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int32_t log2_int(uint32_t val)
{
    uint32_t r;
    uint32_t tmp;
    uint32_t exp = 0;
    exp = __builtin_clz(val);
    val <<= exp - 1;
    r = (32 - exp) << 24;
    tmp = val + (val >> 1); if (!(tmp & 0x80000000)) { val = tmp; r -= 9814042; }
    tmp = val + (val >> 2); if (!(tmp & 0x80000000)) { val = tmp; r -= 5401057; }
    tmp = val + (val >> 3); if (!(tmp & 0x80000000)) { val = tmp; r -= 2850868; }
    tmp = val + (val >> 4); if (!(tmp & 0x80000000)) { val = tmp; r -= 1467383; }
    tmp = val + (val >> 5); if (!(tmp & 0x80000000)) { val = tmp; r -= 744810; }
    tmp = val + (val >> 6); if (!(tmp & 0x80000000)) { val = tmp; r -= 375270; }
    tmp = val + (val >> 7); if (!(tmp & 0x80000000)) { val = tmp; r -= 188362; }
    val = 0x80000000 - val;
    tmp = val - (val >> 5);
    val = tmp - (val >> 2);
    r -= (val) >> 6;
    return (r) >> 10;
}