4 inline cell log2(cell x)
7 #if defined(FACTOR_X86)
11 asm ("bsr %1, %0;":"=r"(n):"r"(x));
13 #elif defined(FACTOR_AMD64)
15 _BitScanReverse64(&n,x);
17 asm ("bsr %1, %0;":"=r"(n):"r"(x));
19 #elif defined(FACTOR_PPC)
20 asm ("cntlzw %1, %0;":"=r"(n):"r"(x));
23 #error Unsupported CPU
28 inline cell rightmost_clear_bit(cell x)
30 return log2(~x & (x + 1));
33 inline cell rightmost_set_bit(cell x)
35 return log2(x & (~x + 1));
38 inline cell popcount(cell x)
41 u64 k1 = 0x5555555555555555ll;
42 u64 k2 = 0x3333333333333333ll;
43 u64 k4 = 0x0f0f0f0f0f0f0f0fll;
44 u64 kf = 0x0101010101010101ll;
54 x = x - ((x >> 1) & k1); // put count of each 2 bits into those 2 bits
55 x = (x & k2) + ((x >> 2) & k2); // put count of each 4 bits into those 4 bits
56 x = (x + (x >> 4)) & k4 ; // put count of each 8 bits into those 8 bits
57 x = (x * kf) >> ks; // returns 8 most significant bits of x + (x<<8) + (x<<16) + (x<<24) + ...