Converts a byte array into a hexadecimal string. - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Converts a byte array into a hexadecimal string.

Demo Code


//package com.java2s;
import java.math.BigInteger;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] array = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(toHex(array));
    }//from  w  ww  .j ava2s. co m

    /**
     * Converts a byte array into a hexadecimal string.
     * From https://crackstation.net/hashing-security.htm
     * 
     * @param array
     *            the byte array to convert
     * @return a length*2 character string encoding the byte array
     */
    public static String toHex(final byte[] array) {
        final BigInteger bi = new BigInteger(1, array);
        final String hex = bi.toString(16);
        final int paddingLength = (array.length * 2) - hex.length();
        final String res;
        if (paddingLength > 0) {
            res = String.format("%0" + paddingLength + "d", 0) + hex;
        } else {
            res = hex;
        }

        return res;
    }
}

Related Tutorials