CustomBitSet implements Closeable { public byte[] toByteArray() { byte[] dst = new byte[buf.capacity()]; buf.get(dst); return dst; } private  CustomBitSet(final int nrBytes); private  CustomBitSet(final int nrBytes, final ByteBuffer buffer); static CustomBitSet withByteBuffer(final int numBytes, ByteBuffer byteBuffer); static CustomBitSet withByteLength(final int nrBytes); static CustomBitSet withBitLength(final int nrBits); void setBit(final long bitOffset); void unsetBit(final long bitOffset); int readInt(long startBitIndex, long endBitIndex); byte[] toByteArray(); String toString(); long findNthBitSetAfter(long startBitIndex, int n); long nextSetBit(long index); long nextSetBitAfter(long index); boolean isBitSet(long index); @Override void close();  }
@Test public void testTurnOffNthLeftmostBits() { for(int value = 0; value < 256; ++value) { for(int bitsToTurnOff = 0; bitsToTurnOff < 8; ++bitsToTurnOff) { byte[] values = new byte[1]; values[0] = (byte) value; BitSet bitSet = BitSet.valueOf(values); int bitsToTurnOffInBitSet = bitsToTurnOff; while (0 < bitsToTurnOffInBitSet && !bitSet.isEmpty()) { bitSet.flip(bitSet.previousSetBit(7)); bitsToTurnOffInBitSet--; } values = bitSet.toByteArray(); int actual = BitUtils.turnOffNthLeftmostSetBits(value, bitsToTurnOff); if (values.length == 0) { Assert.assertEquals(actual, 0, "Value " + Integer.toBinaryString(value) + " with " + bitsToTurnOff + " bits to turn off => " + Integer.toBinaryString(actual)); } else { Assert.assertEquals(actual, values[0] & 0xFF, "Value " + Integer.toBinaryString(value) + " with " + bitsToTurnOff + " bits to turn off => " + Integer.toBinaryString(actual)); } } } }