More classes for galois
[IRC.git] / Robust / src / ClassLibrary / Integer.java
index 1f7909f4584b18eaf0b7448a8c3683947afe29fc..6943cf87067aa7bf3315c6e26ce20767bd1f191f 100644 (file)
@@ -116,4 +116,22 @@ public class Integer {
     // Returns just -1 or 1 on inequality; doing math might overflow.
     return value > i.value?1:-1;
   }
+  
+  public static int bitCount(int x) {
+    // Successively collapse alternating bit groups into a sum.
+    x = ((x >> 1) & 0x55555555) + (x & 0x55555555);
+    x = ((x >> 2) & 0x33333333) + (x & 0x33333333);
+    x = ((x >> 4) & 0x0f0f0f0f) + (x & 0x0f0f0f0f);
+    x = ((x >> 8) & 0x00ff00ff) + (x & 0x00ff00ff);
+    return ((x >> 16) & 0x0000ffff) + (x & 0x0000ffff);
+  }
+  
+  public static int numberOfLeadingZeros(int value) {
+    value |= value >>> 1;
+    value |= value >>> 2;
+    value |= value >>> 4;
+    value |= value >>> 8;
+    value |= value >>> 16;
+    return bitCount(~value);
+  }
 }