16进制字符串 和 文本字符串 相互转换的工具类

时间:2021-12-08 17:50:55
/**
 * 16进制字符串 和 文本字符串 相互转换的工具类
 */
public class HexStringUtil {

    /** 16进制能用到的所有字符 */
    private static String hexCharsStr = "0123456789ABCDEF";

    /** 16进制能用到的所有字符数组 */
    private static char[] hexCharsArr = hexCharsStr.toCharArray();

    /**
     * 0123456789ABCDEF -> 0 ~ 15
     */
    private static byte oneHexChar2Byte(char c) {
        byte b = (byte) hexCharsStr.indexOf(c);
        return b;
    }

    /**
     * 0 ~ 15 -> 0123456789ABCDEF
     */
    private static char byte2OneHexChar(byte b) {
        char c = hexCharsArr[b];
        return c;
    }

    /**
     * 两个16进制字符 -> 1个byte数值
     */
    private static byte twoHexChar2Byte(char high, char low) {
        byte b = (byte) (oneHexChar2Byte(high) << 4 | oneHexChar2Byte(low));
        return b;
    }

    /**
     * 1个byte数值 -> 两个16进制字符
     */
    private static char[] byte2TwoHexChar(byte b) {
        char[] chars = new char[2];

        // 高4位, 与操作 1111 0000
        byte high4bit = (byte) ((b & 0x0f0) >> 4);
        chars[0] = byte2OneHexChar((byte) high4bit);

        // 低四位, 与操作 0000 1111
        byte low4bit = (byte) (b & 0x0f);
        chars[1] = byte2OneHexChar((byte) low4bit);

        return chars;
    }

    /**
     * 文本字符串 -> 十六进制字符串
     */
    public static String str2HexString(String str) {
        byte[] bytes = str.getBytes();
        return bytes2HexString(bytes);
    }

    /**
     * byte数组 -> 十六进制字符串
     */
    public static final String bytes2HexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            char[] chars = byte2TwoHexChar(bytes[i]);
            sb.append(new String(chars));
        }
        return sb.toString();
    }

    /**
     * 十六进制字符串 -> 文本字符串
     */
    public static String hexString2Str(String hexStr) {
        byte[] bytes = hexString2Bytes(hexStr);
        return new String(bytes);
    }

    /**
     * 16进制的字符串 -> byte数组
     */
    public static byte[] hexString2Bytes(String hexStr) {
        int length = (hexStr.length() / 2);
        byte[] bytes = new byte[length];
        char[] charArr = hexStr.toCharArray();
        for (int i = 0; i < length; i++) {
            int position = i * 2;
            bytes[i] = twoHexChar2Byte(charArr[position], charArr[position + 1]);
        }
        return bytes;
    }

}