NumSetBits { public static long getNumSetBits(byte[] leds, long offset, long length) { long firstBitIndex = offset; long lastBitIndex = firstBitIndex + length - 1; byte firstByteIndex = (byte) (firstBitIndex / 8); byte lastByteIndex = (byte) ((firstBitIndex + length - 1) / 8); long totalSetBits = 0L; if (firstByteIndex != lastByteIndex) { totalSetBits += getNumSetBitsBetweenWholeBytes(leds, firstByteIndex + 1, lastByteIndex - 1); totalSetBits += getNumSetBits(leds[firstByteIndex], (int) (firstBitIndex % 8), 7); totalSetBits += getNumSetBits(leds[lastByteIndex], 0, (int) (lastBitIndex % 8)); } else { totalSetBits += getNumSetBits(leds[firstByteIndex], (int) (firstBitIndex % 8), (int) (lastBitIndex % 8)); } return totalSetBits; }  static long getNumSetBits(byte[] leds, long offset, long length); static int getNumSetBits(byte b, int startOffset, int endOffset); static long getNumSetBitsBetweenWholeBytes(byte[] array,
			int firstByte, int lastByte);  }
@Test public void getNumSetBits_TestAllBytes() { for (int number = 0; number <= 255; number++) { int expected = 0; for (char c : Integer.toBinaryString(number).toCharArray()) { if (c == '1') { expected++; } } assertEquals(expected, NumSetBits.getNumSetBits((byte) number, 0, 7)); } }
@Test public void getNumSetBits_TestOffsetChecking() { assertEquals(8, NumSetBits.getNumSetBits((byte) 255, 0, 7)); assertEquals(6, NumSetBits.getNumSetBits((byte) 255, 1, 6)); assertEquals(4, NumSetBits.getNumSetBits((byte) 255, 2, 5)); assertEquals(2, NumSetBits.getNumSetBits((byte) 255, 3, 4)); assertEquals(1, NumSetBits.getNumSetBits((byte) 255, 4, 4)); }
@Test public void getNumSetBits_ByteArrayWithOffsetAndLength() { byte[] array = new byte[] { (byte) 100, (byte) 255, (byte) 255, (byte) 175 }; assertEquals(1, NumSetBits.getNumSetBits(array, 3, 3)); assertEquals(20, NumSetBits.getNumSetBits(array, 3, 26)); }