Takes a byte array and returns it HEX representation. - Java java.lang

Java examples for java.lang:byte Array to hex

Description

Takes a byte array and returns it HEX representation.

Demo Code


//package com.java2s;

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

    /**
     * Takes a byte array and returns it HEX representation.
     * 
     * @param byteArray
     *            the byte array.
     * @return the HEX representation.
     */
    public static String toHexString(byte[] byteArray) {

        if (byteArray != null && byteArray.length != 0) {

            StringBuilder builder = new StringBuilder(byteArray.length * 3);
            for (int i = 0; i < byteArray.length; i++) {
                builder.append(String.format("%02X", 0xFF & byteArray[i]));

                if (i < byteArray.length - 1) {
                    builder.append(' ');
                }
            }
            return builder.toString();
        } else {
            return "--";
        }
    }
}

Related Tutorials