gb2312 string (including noon) to hexadecimal string and reverse escape original character

Reference article:

https://blog.csdn.net/weixin_42696271/article/details/114100244

/**
     * 中文字符串转16进制
     * gb2312编码字符串转义正确
     * @param text
     * @return
     */
    public static String strToHexStr_gb2312(String text) {
    
    
        byte[] arr = new byte[0];
        try {
    
    
            arr = text.getBytes("GB2312");
        } catch (UnsupportedEncodingException e) {
    
    
            throw new RuntimeException(e);
        }

        //将数组转为16进制字符串
        String hexStr = "";
        for (int i = 0; i < arr.length; i++) {
    
    
            String str = byteToHex(arr[i]);
            hexStr = hexStr + str;
        }
        if(!"".equals(hexStr)){
    
    
            hexStr=hexStr.toUpperCase();
        }
        return hexStr;
    }
//将gb2312生成的16进制编码转换成汉字
    public static String stringToGbk(String string) throws Exception{
    
    
        byte[] bytes = new byte[string.length() / 2];
        for(int i = 0; i < bytes.length; i ++){
    
    
            byte high = Byte.parseByte(string.substring(i * 2, i * 2 + 1), 16);
            byte low = Byte.parseByte(string.substring(i * 2 + 1, i * 2 + 2), 16);
            bytes[i] = (byte) (high << 4 | low);
        }
        String result = new String(bytes, "gbk");
        return result;
    }

Guess you like

Origin blog.csdn.net/qq_40351360/article/details/127686599