Takes a HEX stream and returns the corresponding byte array. - Java java.lang

Java examples for java.lang:byte Array to hex

Description

Takes a HEX stream and returns the corresponding byte array.

Demo Code


//package com.java2s;

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

    /**
     * Takes a HEX stream and returns the corresponding byte array.
     * 
     * @param hexStream
     *            the HEX stream.
     * @return the byte array.
     */
    public static byte[] hexStreamToByteArray(String hexStream) {
        int length = hexStream.length();

        byte[] data = new byte[length / 2];
        for (int i = 0; i < length; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexStream.charAt(i), 16) << 4) + Character
                    .digit(hexStream.charAt(i + 1), 16));
        }
        return data;
    }
}

Related Tutorials