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

Java examples for java.lang:byte Array Convert

Description

Converts a string of hexadecimal characters into a byte array.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String hex = "java2s.com";
        System.out.println(java.util.Arrays.toString(fromHex(hex)));
    }//from  ww  w.j  a  v a2 s .  c o  m

    /**
     * Converts a string of hexadecimal characters into a byte array.
     * From https://crackstation.net/hashing-security.htm.
     * 
     * @param hex
     *            the hex string
     * @return the hex string decoded into a byte array
     */
    public static byte[] fromHex(final String hex) {
        final byte[] binary = new byte[hex.length() / 2];
        for (int i = 0; i < binary.length; i++) {
            binary[i] = (byte) Integer.parseInt(
                    hex.substring(2 * i, 2 * i + 2), 16);
        }
        return binary;
    }
}

Related Tutorials