]> gitweb.factorcode.org Git - factor.git/blob - vm/bitwise_hacks.hpp
Merge branch 'master' of git://factorcode.org/git/factor
[factor.git] / vm / bitwise_hacks.hpp
1 namespace factor
2 {
3
4 /* These algorithms were snarfed from various places. I did not come up with them myself */
5
6 inline cell popcount(cell x)
7 {
8 #ifdef FACTOR_64
9         u64 k1 = 0x5555555555555555ll;
10         u64 k2 = 0x3333333333333333ll;
11         u64 k4 = 0x0f0f0f0f0f0f0f0fll;
12         u64 kf = 0x0101010101010101ll;
13         cell ks = 56;
14 #else
15         u32 k1 = 0x55555555;
16         u32 k2 = 0x33333333;
17         u32 k4 = 0xf0f0f0f;
18         u32 kf = 0x1010101;
19         cell ks = 24;
20 #endif
21
22         x =  x       - ((x >> 1)  & k1); // put count of each 2 bits into those 2 bits
23         x = (x & k2) + ((x >> 2)  & k2); // put count of each 4 bits into those 4 bits
24         x = (x       +  (x >> 4)) & k4 ; // put count of each 8 bits into those 8 bits
25         x = (x * kf) >> ks; // returns 8 most significant bits of x + (x<<8) + (x<<16) + (x<<24) + ...
26
27         return (cell)x;
28 }
29
30 inline cell log2(cell x)
31 {
32 #if defined(FACTOR_X86)
33         cell n;
34         asm ("bsr %1, %0;":"=r"(n):"r"(x));
35 #elif defined(FACTOR_AMD64)
36         cell n;
37         asm ("bsr %1, %0;":"=r"(n):"r"(x));
38 #else
39         cell n = 0;
40 #ifdef FACTOR_64
41         if (x >= (u64)1 << 32) { x >>= 32; n += 32; }
42 #endif
43         if (x >= (u32)1 << 16) { x >>= 16; n += 16; }
44         if (x >= (u32)1 <<  8) { x >>=  8; n +=  8; }
45         if (x >= (u32)1 <<  4) { x >>=  4; n +=  4; }
46         if (x >= (u32)1 <<  2) { x >>=  2; n +=  2; }
47         if (x >= (u32)1 <<  1) {           n +=  1; }
48 #endif
49         return n;
50 }
51
52 inline cell rightmost_clear_bit(cell x)
53 {
54         return log2(~x & (x + 1));
55 }
56
57 inline cell rightmost_set_bit(cell x)
58 {
59         return log2(x & -x);
60 }
61
62 }