Encode a byte array as a hexadecimal string - Java java.lang

Java examples for java.lang:byte Array to String

Description

Encode a byte array as a hexadecimal string

Demo Code


//package com.java2s;

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

    /**
     * Encode a byte array as a hexadecimal string
     *
     * @param   bytes
     * @return
     */
    public static String toHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {

            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }

            hexString.append(hex);
        }

        return hexString.toString();
    }
}

Related Tutorials