java util - Unicode轉換工具


 

測試代碼

package cn.java.codec.unicode;

public class Test {

    public static void main(String[] args) throws Exception {
        String str = "test中文";
        String unicodeEncode = UnicodeUtil.encode(str);
        System.out.println("UnicodeUtil.encode Result : " + unicodeEncode);
        
        str = UnicodeUtil.decode(unicodeEncode);
        System.out.println("UnicodeUtil.decode Result : " + str);
    }
}

輸出內容

UnicodeUtil.encode Result : \u0074\u0065\u0073\u0074\u4e2d\u6587
UnicodeUtil.decode Result : test中文

 

 

工具類

package cn.java.codec.unicode;

/**
 * 每六位描述一個字節
 * @author zhouzhian
 */
public class UnicodeUtil {
    
    /**
     * 字符串編碼成Unicode編碼
     */
    public static String encode(String src) throws Exception {
        char c;
        StringBuilder str = new StringBuilder();
        int intAsc;
        String strHex;
        for (int i = 0; i < src.length(); i++) {
            c = src.charAt(i);
            intAsc = (int) c;
            strHex = Integer.toHexString(intAsc);
            if (intAsc > 128)
                str.append("\\u" + strHex);
            else
                str.append("\\u00" + strHex); // 低位在前面補00
        }
        return str.toString();
    }
    
    /**
     * Unicode解碼成字符串
     * @param src
     * @return
     */
    public static String decode(String src) {
        int t =  src.length() / 6;
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < t; i++) {
            String s = src.substring(i * 6, (i + 1) * 6); // 每6位描述一個字節
            // 高位需要補上00再轉
            String s1 = s.substring(2, 4) + "00";
            // 低位直接轉
            String s2 = s.substring(4);
            // 將16進制的string轉為int
            int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);
            // 將int轉換為字符
            char[] chars = Character.toChars(n);
            str.append(new String(chars));
        }
        return str.toString();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM