public final class BitArray {\r
\r
private int[] bits;\r
- private int size;\r
+ private final int size;\r
\r
public BitArray(int size) {\r
this.size = size;\r
this.bits = makeArray(size);\r
}\r
\r
+ public int getSize() {\r
+ return size;\r
+ }\r
+\r
/**\r
* @param i bit to get\r
* @return true iff bit i is set\r
*\r
* @param i first bit to set\r
* @param newBits the new value of the next 32 bits. Note again that the least-significant bit\r
- * corresponds to bit i, the next-least-significant to i+1, and so on.\r
+ * corresponds to bit i, the next-least-significant to i+1, and so on.\r
*/\r
public void setBulk(int i, int newBits) {\r
bits[i >> 5] = newBits;\r
}\r
}\r
\r
+ /**\r
+ * Efficient method to check if a range of bits is set, or not set.\r
+ *\r
+ * @param start start of range, inclusive.\r
+ * @param end end of range, exclusive\r
+ * @param value if true, checks that bits in range are set, otherwise checks that they are not set\r
+ * @return true iff all bits are set or not set in range, according to value argument\r
+ * @throws IllegalArgumentException if end is less than or equal to start\r
+ */\r
+ public boolean isRange(int start, int end, boolean value) {\r
+ if (end < start) {\r
+ throw new IllegalArgumentException();\r
+ }\r
+ if (end == start) {\r
+ return true; // empty range matches\r
+ }\r
+ end--; // will be easier to treat this as the last actually set bit -- inclusive \r
+ int firstInt = start >> 5;\r
+ int lastInt = end >> 5;\r
+ for (int i = firstInt; i <= lastInt; i++) {\r
+ int firstBit = i > firstInt ? 0 : start & 0x1F;\r
+ int lastBit = i < lastInt ? 31 : end & 0x1F;\r
+ int mask;\r
+ if (firstBit == 0 && lastBit == 31) {\r
+ mask = -1;\r
+ } else {\r
+ mask = 0;\r
+ for (int j = firstBit; j <= lastBit; j++) {\r
+ mask |= 1 << j;\r
+ }\r
+ }\r
+ if (value) {\r
+ if ((bits[i] & mask) != mask) {\r
+ return false;\r
+ }\r
+ } else {\r
+ if ((bits[i] & mask) != 0) {\r
+ return false;\r
+ }\r
+ }\r
+ }\r
+ return true;\r
+ }\r
+\r
/**\r
* @return underlying array of ints. The first element holds the first 32 bits, and the least\r
- * significant bit is bit 0.\r
+ * significant bit is bit 0.\r
*/\r
public int[] getBitArray() {\r
return bits;\r
}\r
- \r
+\r
/**\r
* Reverses all bits in the array.\r
*/\r
}\r
bits = newBits;\r
}\r
- \r
+\r
private static int[] makeArray(int size) {\r
int arraySize = size >> 5;\r
if ((size & 0x1F) != 0) {\r