1. 程式人生 > >簡訊中的的 UCS2的編碼與解碼方法(java)

簡訊中的的 UCS2的編碼與解碼方法(java)

最近,做一個關於SMS的程式,需要對中文部分進行UCS編碼,這裡用了兩個函式,可以將簡訊中的UCS2字串在UCS2和GBK之間裝換。記錄以下程式碼:

    /**
     * UCS2解碼
     * 
     * @param src
     *            UCS2 源串
     * @return 解碼後的UTF-16BE字串
     */
    public static String DecodeUCS2(String src) {
        byte[] bytes = new byte[src.length() / 2];

        for (int
i = 0; i < src.length(); i += 2) { bytes[i / 2] = (byte) (Integer .parseInt(src.substring(i, i + 2), 16)); } String reValue; try { reValue = new String(bytes, "UTF-16BE"); } catch (UnsupportedEncodingException e) { throw
new PduDecodeException(e); } return reValue; } /** * UCS2編碼 * * @param src * UTF-16BE編碼的源串 * @return 編碼後的UCS2串 */ public static String EncodeUCS2(String src) { byte[] bytes; try { bytes = src.getBytes("UTF-16BE"
); } catch (UnsupportedEncodingException e) { throw new PduEncodeException(e); } StringBuffer reValue = new StringBuffer(); StringBuffer tem = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { tem.delete(0, tem.length()); tem.append(Integer.toHexString(bytes[i] & 0xFF)); if(tem.length()==1){ tem.insert(0, '0'); } reValue.append(tem); } return reValue.toString().toUpperCase(); }