Java convert a byte array to hex string

www.la‮tu‬turi.com
Java convert a byte array to hex string
/**
 * @author lautturi.com
 * Java example: Converts a byte array to hex string
 */

public class Lautturi {
	private static void byte2hex(byte b, StringBuffer buf) {
        char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        int high = ((b & 0xf0) >> 4);
        int low = (b & 0x0f);
        buf.append(hexChars[high]);
        buf.append(hexChars[low]);
    }

	public static void main(String[] args)  {
		
		byte[] block = {106, 97, 118, 97};
		StringBuffer buf = new StringBuffer();
        int len = block.length;
        for (int i = 0; i < len; i++) {
            byte2hex(block[i], buf);
            if (i < len-1) {
                buf.append(":");
            }
        }
        String str = buf.toString();

        System.out.println(str);
	}
}
Created Time:2017-09-23 12:01:59  Author:lautturi