ByteAndBitConverter { public static String toHex(boolean[] bits) { StringBuilder hex = new StringBuilder(); boolean[] niceBits = null; if (bits.length % 4 == 0) { niceBits = bits; } else { niceBits = new boolean[4 * ((bits.length / 4) + 1)]; int offset = 4 - (bits.length % 4); System.arraycopy(bits, 0, niceBits, offset, bits.length); } StringBuilder binb = new StringBuilder(); for (boolean niceBit : niceBits) { binb.append(niceBit ? "1" : "0"); } String bin = binb.toString(); for (int i = 0; i < bin.length() / 4; i++) { String digit = bin.substring(i * 4, i * 4 + 4); Integer dec = Integer.parseInt(digit, 2); String hexStr = Integer.toHexString(dec); hex.append(hexStr); } if (hex.length() % 2 != 0) { hex.insert(0, "0"); } return hex.toString(); } private  ByteAndBitConverter(); static byte[] toByteArray(long value); static byte[] toByteArray(int value); static BitSet intToBitSet(int i); static Boolean[] toBoolean(String hex); static String toHex(boolean[] bits); static String toHex(List<Boolean> bits);  }
@Test public void testToHex() { Assert.assertThat(ByteAndBitConverter.toHex( new boolean[]{false, false, false, false, false, false, false, false}), Is.is("00")); Assert.assertThat( ByteAndBitConverter.toHex(new boolean[]{true, true, true, true, true, true, true, true}), Is.is("ff")); Assert.assertThat( ByteAndBitConverter.toHex(new boolean[]{true, true, true, true, true, true, true}), Is.is("7f")); Assert.assertThat( ByteAndBitConverter.toHex(new boolean[]{true, true, true, true, true, true}), Is.is("3f")); Assert.assertThat(ByteAndBitConverter.toHex(new boolean[]{true, true, true, true, true}), Is.is("1f")); Assert.assertThat(ByteAndBitConverter.toHex(new boolean[]{true, true, true, true}), Is.is("0f")); Assert.assertThat( ByteAndBitConverter .toHex(new boolean[]{false, true, true, true, true, true, true, true, true}), Is.is("00ff")); Assert.assertThat(ByteAndBitConverter.toHex( new boolean[]{true, true, true, true, true, true, true, true, true}), Is.is("01ff")); Assert.assertThat( ByteAndBitConverter.toHex(Arrays .asList((new Boolean[]{true, true, true, true, true, true, true, true, true}))), Is.is("01ff")); }