1 /*(C) Timothy B. Terriberry (tterribe@xiph.org) 2001-2009 CC0 (Public domain).
2 * See LICENSE file for details. */
6 /*The fastest fallback strategy for platforms with fast multiplication appears
7 to be based on de Bruijn sequences~\cite{LP98}.
8 Tests confirmed this to be true even on an ARM11, where it is actually faster
9 than using the native clz instruction.
10 Define ILOG_NODEBRUIJN to use a simpler fallback on platforms where
11 multiplication or table lookups are too expensive.
14 author="Charles E. Leiserson and Harald Prokop",
15 title="Using de {Bruijn} Sequences to Index a 1 in a Computer Word",
18 note="\url{http://supertech.csail.mit.edu/papers/debruijn.pdf}"
20 static UNNEEDED const unsigned char DEBRUIJN_IDX32[32]={
21 0, 1,28, 2,29,14,24, 3,30,22,20,15,25,17, 4, 8,
22 31,27,13,23,21,19,16, 7,26,12,18, 6,11, 5,10, 9
25 /* We always compile these in, in case someone takes address of function. */
31 int ilog32(uint32_t _v){
32 /*On a Pentium M, this branchless version tested as the fastest version without
33 multiplications on 1,000,000,000 random 32-bit integers, edging out a
34 similar version with branches, and a 256-entry LUT version.*/
35 # if defined(ILOG_NODEBRUIJN)
53 /*This de Bruijn sequence version is faster if you have a fast multiplier.*/
63 ret+=DEBRUIJN_IDX32[_v*0x77CB531U>>27&0x1F];
68 int ilog32_nz(uint32_t _v)
73 int ilog64(uint64_t _v){
74 # if defined(ILOG_NODEBRUIJN)
79 m=(_v>0xFFFFFFFFU)<<5;
97 /*If we don't have a 64-bit word, split it into two 32-bit halves.*/
98 # if LONG_MAX<9223372036854775807LL
103 m=(_v>0xFFFFFFFFU)<<5;
112 ret+=DEBRUIJN_IDX32[v*0x77CB531U>>27&0x1F];
114 /*Otherwise do it in one 64-bit operation.*/
116 static const unsigned char DEBRUIJN_IDX64[64]={
117 0, 1, 2, 7, 3,13, 8,19, 4,25,14,28, 9,34,20,40,
118 5,17,26,38,15,46,29,48,10,31,35,54,21,50,41,57,
119 63, 6,12,18,24,27,33,39,16,37,45,47,30,53,49,56,
120 62,11,23,32,36,44,52,55,61,22,43,51,60,42,59,58
131 ret+=DEBRUIJN_IDX64[_v*0x218A392CD3D5DBF>>58&0x3F];
137 int ilog64_nz(uint64_t _v)