中文与UniCode互相转换

public class UnicodeTest {

    public static void main(String[] args) {
        String str = "中文测试";
        String s = toUnicode(str);
        System.out.println(toUnicode(str));
        System.out.println(decodeUnicode(s));

    }

    /**
     * 汉字转UniCode
     *
     * @param s 要编码的中文字符串
     * @return 编码后的字符串
     */
    public static String toUnicode(String s) {
        String[] as = new String[s.length()];
        StringBuilder s1 = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            as[i] = Integer.toHexString(s.charAt(i) & 0xffff);
            s1.append("\\u").append(as[i]);
        }
        return s1.toString();
    }

    /**
     * unicode编码转中文
     */
    public static String decodeUnicode(final String dataStr) {
        int start = 0;
        int end;
        final StringBuilder buffer = new StringBuilder();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr;
            if (end == -1) {
                charStr = dataStr.substring(start + 2);
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            // 16进制parse整形字符串。
            char letter = (char) Integer.parseInt(charStr, 16);
            buffer.append(letter);
            start = end;
        }
        return buffer.toString();
    }

    /**
     * 汉字转换成二进制字符串
     *
     * @param str 需要编码的字符串
     * @return 编码后的字符串
     */
    public static String strToBinStr(String str) {
        char[] chars = str.toCharArray();
        StringBuilder result = new StringBuilder();
        for (char aChar : chars) {
            result.append(Integer.toBinaryString(aChar));
            result.append(" ");
        }
        return result.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41988225/article/details/107632395