class 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();

}