+bitCount
authorClaus Gittinger <cg@exept.de>
Sat, 24 Jan 2009 21:40:24 +0100
changeset 11493 6496a8ef2fc9
parent 11492 4532fa5c3224
child 11494 f93be1a07572
+bitCount
SmallInteger.st
--- a/SmallInteger.st	Sat Jan 24 21:40:03 2009 +0100
+++ b/SmallInteger.st	Sat Jan 24 21:40:24 2009 +0100
@@ -882,6 +882,48 @@
     "
 !
 
+bitCount
+    "return the number of 1-bits in the receiver"
+
+%{  /* NOCONTEXT */
+    int _cnt = 0;
+    int _self = __intVal(self);
+    //                  0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15
+    int _counts[16] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
+
+    _cnt = _counts[_self & 0xF]; _self = _self>>4;         // ______xx
+    _cnt += _counts[_self & 0xF]; _self = _self>>4;
+    if (_self != 0) {
+        _cnt += _counts[_self & 0xF]; _self = _self>>4;     // xxxxxx__ 
+        _cnt += _counts[_self & 0xF]; _self = _self>>4;      
+        _cnt += _counts[_self & 0xF]; _self = _self>>4;      
+        _cnt += _counts[_self & 0xF]; _self = _self>>4;      
+        _cnt += _counts[_self & 0xF]; _self = _self>>4;      
+        _cnt += _counts[_self & 0xF]; _self = _self>>4;      
+# if __POINTER_SIZE__ == 8
+        if (_self != 0) {
+            _cnt += _counts[_self & 0xF]; _self = _self>>4;      
+            _cnt += _counts[_self & 0xF]; _self = _self>>4;      
+            _cnt += _counts[_self & 0xF]; _self = _self>>4;      
+            _cnt += _counts[_self & 0xF]; _self = _self>>4;      
+            _cnt += _counts[_self & 0xF]; _self = _self>>4;      
+            _cnt += _counts[_self & 0xF]; _self = _self>>4;      
+            _cnt += _counts[_self & 0xF]; _self = _self>>4;      
+            _cnt += _counts[_self & 0xF]; _self = _self>>4;      
+        }
+# endif
+    }
+
+    RETURN ( __MKSMALLINT(_cnt));
+%}
+
+    "
+     1 to:10000 do:[:n |
+        self assert:(n bitCount = ((n printStringRadix:2) occurrencesOf:$1))
+     ]
+    "
+!
+
 bitInvert
     "return the value of the receiver with all bits inverted"
 
@@ -3756,5 +3798,5 @@
 !SmallInteger class methodsFor:'documentation'!
 
 version
-    ^ '$Header: /cvs/stx/stx/libbasic/SmallInteger.st,v 1.171 2008-04-23 12:07:08 stefan Exp $'
+    ^ '$Header: /cvs/stx/stx/libbasic/SmallInteger.st,v 1.172 2009-01-24 20:40:24 cg Exp $'
 ! !