1 module dkh.bitop;
2 
3 public import core.bitop;
4 
5 static if (!__traits(compiles, popcnt(ulong.max))) {
6     public import core.bitop : popcnt;
7     int popcnt(ulong v) {
8         return popcnt(cast(uint)(v)) + popcnt(cast(uint)(v>>32));
9     }
10 }
11 
12 /// poppar(v) == popcnt(v) % 2
13 bool poppar(uint v) {
14     v^=v>>1; v^=v>>2;
15     v&=0x11111111U;
16     v*=0x11111111U;
17     return ((v>>28) & 1) != 0;
18 }
19 
20 /// ditto
21 bool poppar(ulong v) {
22     v^=v>>1; v^=v>>2;
23     v&=0x1111111111111111UL;
24     v*=0x1111111111111111UL;
25     return ((v>>60) & 1) != 0;
26 }
27 
28 ///
29 unittest {
30     import std.random;
31     foreach (i; 0..100) {
32         uint v = uniform!"[]"(0U, uint.max);
33         assert(poppar(v) == popcnt(v) % 2);
34     }
35     foreach (i; 0..100) {
36         ulong v = uniform!"[]"(0UL, ulong.max);
37         assert(poppar(v) == popcnt(v) % 2);
38     }
39 }