package shop.alien.util.codechange;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ssk
 * @version 1.0
 * @date 2020/8/10 9:01
 */
public class ZhToUnicode {

    public static void main(String[] args) {
        String sourceData = "这是原始的数据！！！";
        String unicodeEncode = unicodeEncode(sourceData);
        System.out.println("编码结果：" + unicodeEncode);

        String unicodeDecode = unicodeDecode(unicodeEncode);
        System.out.println("解码结果：" + unicodeDecode);
    }

    /**
     * 中文转Unicode
     *
     * @param string 中文内容
     * @return 转换后内容
     */
    public static String unicodeEncode(String string) {
        char[] utfBytes = string.toCharArray();
        StringBuilder unicodeBytes = new StringBuilder();
        for (char utfByte : utfBytes) {
            String hexB = Integer.toHexString(utfByte);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes.append("\\u").append(hexB);
        }
        return unicodeBytes.toString();
    }

    /**
     * Unicode转中文
     *
     * @param string unicode码
     * @return 转换后内容
     */
    public static String unicodeDecode(String string) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }
        return string;
    }

}
