Decodes string of a hexadecimal notation to byte sequence. - Java java.lang

Java examples for java.lang:byte Array to String

Description

Decodes string of a hexadecimal notation to byte sequence.

Demo Code


//package com.java2s;
import java.io.ByteArrayOutputStream;

public class Main {
    public static void main(String[] argv) throws Exception {
        String hex = "java2s.com";
        System.out.println(java.util.Arrays.toString(decode(hex)));
    }//from www . java2s. c o  m

    /**
     * Decodes string of a hexadecimal notation to byte sequence.
     *
     * @param hex String of a hexadecimal notation.
     * @return Byte sequence.
     * @since 0.0.1
     */
    public static byte[] decode(String hex) {
        if (hex == null) {
            return new byte[0];
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        for (int i = 0, n = hex.length(); i < n; i++) {
            output.write(Integer.valueOf(hex.substring(i, ++i + 1), 16));
        }
        return output.toByteArray();
    }
}

Related Tutorials