天天看点

十六进制字符串转成字节数组

1、前言

解析报文中经常会碰到将机器码十六进制字符串转成字节数组,下面的方法挺好用

2、使用

private static String hexStr = "3131303236303832393743323437333530303231340000000000000000";  

    public static void main(String[] args) {
        String collectID = "";
        byte[] bytes = hexStringToByte(hexStr);
        System.out.println(Arrays.toString(bytes));
        for (int i = ; i < bytes.length; i++) {
            collectID += (char) bytes[i];
        }
        System.out.println(collectID);

    }

    /**
     * 16进制字符串转换成字节数组
     *
     * @param hex
     * @return
     */
    public static byte[] hexStringToByte(String hex) {
        byte[] b = new byte[hex.length() / ];
        int j = ;
        for (int i = ; i < b.length; i++) {
            char c0 = hex.charAt(j++);
            char c1 = hex.charAt(j++);
            b[i] = (byte) ((parse(c0) << ) | parse(c1));
        }
        return b;
    }

    private static int parse(char c) {
        if (c >= 'a')
            return (c - 'a' + ) & ;
        if (c >= 'A')
            return (c - 'A' + ) & ;
        return (c - '0') & ;

    }
           

继续阅读