java 汉字与数字字母的编码与解码

直接需求是将汉字转化为数字字母的组合,也就是编码,将这个编码结果进行存储,

回显时需要读取上面这个编码结果进行解码,就可以转换为被编码的汉字了,

具体代码如下,

其中:

str就是需要编码的汉字字符串,

afterEncode是编码结果,该编码结果就可以去和其他非汉字数据一起存储,

afterDecode是解码结果,可以作为汉字显示,

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

public class Encode {
    private static String hexString="0123456789ABCDEF";

    public static void main(String[] args)throws UnsupportedEncodingException {
        String str = "维保日期";
        System.out.println("待编码字符:" + str);
        
        System.out.println("Encode:");
        String afterEncode = encode(str, "GBK");  //中文转换为16进制字符串
        System.out.println("Encode Result:"+afterEncode);
        
//        System.out.println(afterEncode);
        System.out.println("Decode:");
        String afterDecode = decode(afterEncode, "GBK");
        System.out.println("Decode Result:"+afterDecode);
        
    }
    /**
     * 将字符串编码成16进制数字,适用于所有字符(包括中文)
     */
    public static String encode(String str, String charset) throws UnsupportedEncodingException {
         //根据默认编码获取字节数组
         byte[] bytes=str.getBytes(charset);
         StringBuilder sb=new StringBuilder(bytes.length*2);
         //将字节数组中每个字节拆解成2位16进制整数
         for(int i=0;i<bytes.length;i++){
             sb.append(hexString.charAt((bytes[i]&0xf0)>>4));
             sb.append(hexString.charAt((bytes[i]&0x0f)>>0));
         }
         return sb.toString();
    }
    /**
     * 将16进制数字解码成字符串,适用于所有字符(包括中文)
     */
    public static String decode(String bytes, String charset) throws UnsupportedEncodingException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length()/2);
        //将每2位16进制整数组装成一个字节
        for(int i=0;i<bytes.length();i+=2)
            baos.write((hexString.indexOf(bytes.charAt(i))<<4 |hexString.indexOf(bytes.charAt(i+1))));
        return new String(baos.toByteArray(), charset);
    }
    
    
}

测试结果:

待编码字符:维保日期
Encode:
Encode Result:CEACB1A3C8D5C6DA
Decode:
Decode Result:维保日期