Java - Convert byte array to hex string with do while loop

Description

Convert byte array to hex string with do while loop

Demo

//package com.book2s;

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

    /**
     * Convert byte array to hex string.
     * 
     * @param data Target data array.
     * @return Hex string.
     */
    private static String convertToHex(byte[] data) {
        if (data == null || data.length == 0) {
            return null;
        }

        final StringBuffer buffer = new StringBuffer();
        for (int byteIndex = 0; byteIndex < data.length; byteIndex++) {
            int halfbyte = (data[byteIndex] >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                if ((0 <= halfbyte) && (halfbyte <= 9))
                    buffer.append((char) ('0' + halfbyte));
                else
                    buffer.append((char) ('a' + (halfbyte - 10)));
                halfbyte = data[byteIndex] & 0x0F;
            } while (two_halfs++ < 1);
        }

        return buffer.toString();
    }
}

Convert byte array to hex string with do while loop

Related Example