Skip to content

Commit e84f24b

Browse files
committed
Faster popcount, rename bitcount to popcount
2 parents c115bbe + ac075af commit e84f24b

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

core/core.stanza

+22-9
Original file line numberDiff line numberDiff line change
@@ -2950,17 +2950,30 @@ public defn modulo (a:Int, b:Int) -> Int :
29502950
ensure-divide-non-zero(b)
29512951
($prim mod a b)
29522952

2953-
public lostanza defn bitcount (x0:long) -> int :
2954-
var count:int = 0
2955-
for (var x:long = x0, x, x = x & (x - 1)) :
2956-
count = count + 1
2957-
return count
2953+
public lostanza defn popcount (x0:long) -> int :
2954+
var x:long = x0
2955+
x = (x & 0x5555555555555555L) + ((x & 0xaaaaaaaaaaaaaaaaL) >> 1L)
2956+
x = (x & 0x3333333333333333L) + ((x & 0xccccccccccccccccL) >> 2L)
2957+
x = (x & 0x0f0f0f0f0f0f0f0fL) + ((x & 0xf0f0f0f0f0f0f0f0L) >> 4L)
2958+
x = (x & 0x00ff00ff00ff00ffL) + ((x & 0xff00ff00ff00ff00L) >> 8L)
2959+
x = (x & 0x0000ffff0000ffffL) + ((x & 0xffff0000ffff0000L) >> 16L)
2960+
x = (x & 0x00000000ffffffffL) + ((x & 0xffffffff00000000L) >> 32L)
2961+
return (x as int)
2962+
2963+
public lostanza defn popcount-int (x0:int) -> int :
2964+
var x:int = x0
2965+
x = (x & 0x55555555) + ((x & 0xaaaaaaaa) >> 1)
2966+
x = (x & 0x33333333) + ((x & 0xcccccccc) >> 2)
2967+
x = (x & 0x0f0f0f0f) + ((x & 0xf0f0f0f0) >> 4)
2968+
x = (x & 0x00ff00ff) + ((x & 0xff00ff00) >> 8)
2969+
x = (x & 0x0000ffff) + ((x & 0xffff0000) >> 16)
2970+
return x
29582971

2959-
public lostanza defn bitcount (x:ref<Int>) -> ref<Int> :
2960-
return new Int{bitcount(x.value << 32L)}
2972+
public lostanza defn popcount (x:ref<Int>) -> ref<Int> :
2973+
return new Int{popcount-int(x.value)}
29612974

2962-
public lostanza defn bitcount (x:ref<Long>) -> ref<Int> :
2963-
return new Int{bitcount(x.value)}
2975+
public lostanza defn popcount (x:ref<Long>) -> ref<Int> :
2976+
return new Int{popcount(x.value)}
29642977

29652978
;============================================================
29662979
;======================== Longs =============================

0 commit comments

Comments
 (0)