java实现中文或其他语言及标点符号等转换成unicode字符串,或unicode的16进制码转换回文字或符号等

时间:2021-08-24 20:15:24
package org.analysisitem20181016.test;

public class Code128Test2019052201 {

    public static final String UNICODE_PREFIX = "\\u";
    
    public static void main(String[] args) {
        String testStr = "丽塔·洛丝薇瑟";
        String unicodeText1 = encodeToUnicodeText(testStr);
        String unicodeText2 = encodeToUnicodeTextWithoutPrefix(testStr);
        System.out.println(unicodeText1);
        System.out.println(unicodeText2);
        String text = decodeToText(unicodeText2);
        System.out.println(text);
        testStr = "ラピスラズリ(Dawn)";
        unicodeText1 = encodeToUnicodeText(testStr);
        unicodeText2 = encodeToUnicodeTextWithoutPrefix(testStr);
        System.out.println(unicodeText1);
        System.out.println(unicodeText2);
        text = decodeToText(unicodeText2);
        System.out.println(text);
    }
    
    public static String decodeToText(final String unicodeText) {
        String text =  "";
        for(int i = 0; i < unicodeText.length(); i += 4) {
            String currentUnicodeText = unicodeText.substring(i, i + 4);
            char currentText = (char) Integer.parseInt(currentUnicodeText, 16);
            text += currentText;
        }
        return text;
    }
    
    public static String encodeToUnicodeTextWithoutPrefix(final String text) {
        char[] utfChar = text.toCharArray();
        String unicodeStr = "";
        for (int i = 0; i < utfChar.length; i++) {
            String hexB = Integer.toHexString(utfChar[i]);
            while (hexB.length() < 4) {
                hexB = "0" + hexB;
            }
            unicodeStr += hexB;
        }
        return unicodeStr;
    }
    
    public static String encodeToUnicodeText(final String text) {
        char[] utfChar = text.toCharArray();
        String unicodeStr = "";
        for (int i = 0; i < utfChar.length; i++) {
            String hexB = Integer.toHexString(utfChar[i]);
            while (hexB.length() < 4) {
                hexB = "0" + hexB;
            }
            hexB = UNICODE_PREFIX + hexB;
            unicodeStr += hexB;
        }
        return unicodeStr;
    }

}

运行后效果图:

java实现中文或其他语言及标点符号等转换成unicode字符串,或unicode的16进制码转换回文字或符号等