diff --git a/public/java/src/org/broadinstitute/sting/utils/MathUtils.java b/public/java/src/org/broadinstitute/sting/utils/MathUtils.java index a4e9fc7ed..c9ab3b58e 100644 --- a/public/java/src/org/broadinstitute/sting/utils/MathUtils.java +++ b/public/java/src/org/broadinstitute/sting/utils/MathUtils.java @@ -1613,4 +1613,36 @@ public class MathUtils { } + /** + * Creates an integer out of a bitset + * + * @param bitSet the bitset + * @return an integer with the bitset representation + */ + public static int intFrom(final BitSet bitSet) { + int integer = 0; + for (int bitIndex = bitSet.nextSetBit(0); bitIndex >= 0; bitIndex = bitSet.nextSetBit(bitIndex+1)) + integer |= 1 << bitIndex; + + return integer; + } + + /** + * Creates a BitSet representation of a given integer + * + * @param integer the number to turn into a bitset + * @return a bitset representation of the integer + */ + public static BitSet bitSetFrom(int integer) { + BitSet bitSet = new BitSet((int) Math.ceil(Math.sqrt(integer))); + int bitIndex = 0; + while (integer > 0) { + if (integer%2 > 0) + bitSet.set(bitIndex); + bitIndex++; + integer /= 2; + } + return bitSet; + } + } diff --git a/public/java/test/org/broadinstitute/sting/utils/MathUtilsUnitTest.java b/public/java/test/org/broadinstitute/sting/utils/MathUtilsUnitTest.java index 049bdce3e..5b50c91a6 100755 --- a/public/java/test/org/broadinstitute/sting/utils/MathUtilsUnitTest.java +++ b/public/java/test/org/broadinstitute/sting/utils/MathUtilsUnitTest.java @@ -205,6 +205,16 @@ public class MathUtilsUnitTest extends BaseTest { } } + @Test(enabled = true) + public void testIntAndBitSetConversion() { + Assert.assertEquals(428, MathUtils.intFrom(MathUtils.bitSetFrom(428))); + Assert.assertEquals(239847, MathUtils.intFrom(MathUtils.bitSetFrom(239847))); + Assert.assertEquals(12726, MathUtils.intFrom(MathUtils.bitSetFrom(12726))); + Assert.assertEquals(0, MathUtils.intFrom(MathUtils.bitSetFrom(0))); + Assert.assertEquals(1, MathUtils.intFrom(MathUtils.bitSetFrom(1))); + Assert.assertEquals(65536, MathUtils.intFrom(MathUtils.bitSetFrom(65536))); + } + private boolean hasUniqueElements(Object[] x) { for (int i = 0; i < x.length; i++) for (int j = i + 1; j < x.length; j++) @@ -220,10 +230,10 @@ public class MathUtilsUnitTest extends BaseTest { return set.isEmpty(); } - private void p (Object []x) { for (Object v: x) System.out.print((Integer) v + " "); System.out.println(); } + }