Java 字符串转 unicode

package com.test.robot;

import org.junit.Test;

public class Sotodo {

    @Test
    public void test() {
       
        String s = "你好";
       
        String code = convert(s);
       
        System.out.println(code);
       
        System.out.println("\u4f60\u597d");
    }


    public static String convert(String str){
        str = (str == null ? "" : str);
        String tmp;
        StringBuffer sb = new StringBuffer(1000);
        char c;
        int i, j;
        sb.setLength(0);
        for (i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            sb.append("\\u");
            j = (c >>>8); //取出高8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
            sb.append("0");
            sb.append(tmp);
            j = (c & 0xFF); //取出低8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
            sb.append("0");
            sb.append(tmp);
        }
        return (new String(sb));
    }
   
}

猜你喜欢

转载自aa80303857.iteye.com/blog/2347397