package com.its.utils;

public class HexUtils {
    static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    public static byte[] intToBytes(int n) {
        byte[] b = new byte[4];

        for (int ii = 0; ii < 4; ii++) {
            b[ii] = (byte) (n >> (24 - ii * 8));

        }
        return b;
    }

    public static String toHex(int value) {
        byte[] bytes = intToBytes(value);
        return toHex(bytes);
    }

    public static String toHex(byte[] bytes) {
        if (bytes == null || bytes.length == 0)
            return "";
        char[] result = new char[bytes.length * 2];

        for (int ii = 0; ii < bytes.length; ii++) {
            result[ii * 2] = HEX_DIGITS[(bytes[ii] >> 4) & 0xf];
            result[ii * 2 + 1] = HEX_DIGITS[bytes[ii] & 0xf];
        }
        return new String(result);
    }

    public static byte[] decodeHex(String hex) throws IllegalArgumentException {
        if (hex == null)
            throw new IllegalArgumentException("hex == null");
        if (hex.length() % 2 != 0)
            throw new IllegalArgumentException("Unexpected hex string: " + hex);

        byte[] result = new byte[hex.length() / 2];
        for (int ii = 0; ii < result.length; ii++) {
            int d1 = decodeHexDigit(hex.charAt(ii * 2)) << 4;
            int d2 = decodeHexDigit(hex.charAt(ii * 2 + 1));
            result[ii] = (byte) (d1 + d2);
        }
        return result;
    }

    private static int decodeHexDigit(char c) throws IllegalArgumentException {
        if (c >= '0' && c <= '9')
            return c - '0';
        if (c >= 'a' && c <= 'f')
            return c - 'a' + 10;
        if (c >= 'A' && c <= 'F')
            return c - 'A' + 10;
        throw new IllegalArgumentException("Unexpected hex digit: " + c);
    }

    public static String bytes2Hex(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        String tmp = "";
        for (int n = 0; (bytes != null) && (n < bytes.length); ++n) {
            tmp = Integer.toHexString(bytes[n] & 0xFF);
            if (tmp.length() == 1)
                builder.append("0").append(tmp);
            else {
                builder.append(tmp);
            }
        }
        return builder.toString().toLowerCase();
    }
}
