Java - Write code to convert byte array to Hex String

Requirements

Write code to convert byte array to Hex String

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        byte[] bytes = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(toHexString(bytes));
    }//from w  w  w .j a  va 2 s .  c om

    public static final String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < bytes.length; i++) {
            String temp = Integer.toHexString(0xFF & bytes[i]);
            // Take care of bytes 0x00 - 0x0F
            if (temp.length() < 2) {
                sb.append("0");
            }
            sb.append(temp);
        }

        return sb.toString();
    }

    public static final String toHexString(byte[] bytes, boolean toUpperCase) {
        return toUpperCase ? toHexString(bytes).toUpperCase()
                : toHexString(bytes);
    }
}