Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

public class Main {
    static String HEX_CHARS_STRING = "0123456789ABCDEF";

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString.length() % 2 != 0)
            throw new IllegalArgumentException("Hex string length must be even: " + hexString);
        byte[] bytes = new byte[hexString.length() / 2];
        char[] ucChars = hexString.toUpperCase().toCharArray();
        for (int i = 0; i < bytes.length; i++) {
            int index1 = HEX_CHARS_STRING.indexOf(ucChars[2 * i]);
            int index2 = HEX_CHARS_STRING.indexOf(ucChars[2 * i + 1]);
            if (index1 == -1 || index2 == -1)
                throw new IllegalArgumentException("Non-hex character in string: " + hexString);
            bytes[i] = (byte) ((index1 << 4) + index2);
        }
        return bytes;
    }
}