All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dongliu.commons.codec.Hexes Maven / Gradle / Ivy

There is a newer version: 12.0.2
Show newest version
package net.dongliu.commons.codec;

/**
 * Utils method for hex
 *
 * @author Liu Dong
 */
public class Hexes {

    private static final char[] hexArrayUpper = "0123456789ABCDEF".toCharArray();
    private static final char[] hexArrayLower = "0123456789abcdef".toCharArray();

    /**
     * Convert bytes to hex string in low case.
     */
    public static String hexLower(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            char c1 = hexArrayLower[v >>> 4];
            char c2 = hexArrayLower[v & 0x0F];
            hexChars[j * 2] = c1;
            hexChars[j * 2 + 1] = c2;
        }
        return new String(hexChars);
    }

    /**
     * Convert bytes to hex string in upper case.
     */
    public static String hexUpper(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            char c1 = hexArrayUpper[v >>> 4];
            char c2 = hexArrayUpper[v & 0x0F];
            hexChars[j * 2] = c1;
            hexChars[j * 2 + 1] = c2;
        }
        return new String(hexChars);
    }

    /**
     * Convert hex string back to bytes.
     */
    public static byte[] decode(CharSequence str) {
        int len = str.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((toDigit(str.charAt(i)) << 4) + toDigit(str.charAt(i + 1)));
        }
        return data;
    }

    private static int toDigit(char c) {
        if (c >= '0' && c <= '9') {
            return c - '0';
        } else if (c >= 'a' && c <= 'f') {
            return c - 'a';
        } else if (c >= 'A' && c <= 'F') {
            return c - 'A';
        } else {
            throw new IllegalArgumentException("Not a hex char: " + c);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy