Converts a byte array to hex string with leading 0x. - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Converts a byte array to hex string with leading 0x.

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(toHexString0x(byteArray));
    }/*from w ww . ja va 2 s.c  o m*/

    /**
     * Hex characters for use producing human readable strings.
     */
    public static final String hexChars = "0123456789ABCDEF";

    /**
     * Converts a byte array to hex string with leading 0x.
     *
     * @param byteArray A byte array to convert to a hex string.
     * @return A string representing the hex representation of the input.
     */
    public static String toHexString0x(byte[] byteArray) {
        if (byteArray == null) {
            return null;
        }
        return "0x" + toHexString(byteArray);
    }

    /**
     * Converts a byte array to hex string without leading 0x.
     *
     * @param byteArray A byte array to convert to a hex string.
     * @return A string representing the hex representation of the input.
     */
    public static String toHexString(byte[] byteArray) {
        if (byteArray == null) {
            return null;
        }
        final StringBuilder sb = new StringBuilder(2 + 2 * byteArray.length);
        for (final byte b : byteArray) {
            sb.append(hexChars.charAt((b & 0xF0) >> 4)).append(
                    hexChars.charAt((b & 0x0F)));
        }
        return sb.toString();
    }
}

Related Tutorials