中文转成Unicode编码

public class Main {
    public static void main(String[] args) {
        String uname = "编码";
        for (int i = 0; i < uname.length(); i++) {
            char unamechar = uname.charAt(i);
            System.out.println(unamechar + "=" + gbEncoding(String.valueOf(unamechar)));
        }


        String ucode = "\u7f16\u7801";
        System.out.println(ucode);
    }

    /**
     * 把中文转成Unicode编码
     *
     * @param gbString
     * @return
     */
    private static String gbEncoding(final String gbString) {
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
            String hexB = Integer.toHexString(utfBytes[byteIndex]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }
}

你可能感兴趣的:(Java)