2017-07-24 46 views
0

我嘗試使用下面的方法來編碼在java中串串,中國字符區分UTF-16編碼在Java中

String s = "子"; 
byte[] bytesEncoded = Base64.encodeBase64(s.getBytes("UTF-16")); 
String stringEncoded = new String(bytesEncoded); 

當我在Eclipse中運行這段代碼我得到的值/ v9bUA ==

但是一些網上UTF-16轉換器給值一樣4E02

任何人都知道如何將中國的字符轉換爲UTF 16

我已經通過大部分的stackoverflow問題仍然沒有答案。

在此先感謝!

+0

我認爲你應該添加ISO8859-1到你的字符串像:String string1 = new String(encoding1,「ISO8859-1」); –

+0

聽起來像轉換器有一個錯誤,或者你濫用它。如果你不分享*你使用過哪種轉換器,任何人都很難複製你的結果,你不覺得嗎? – dimo414

+1

另外'4E02'看起來像十六進制,而不是Base64。爲什麼你使用Base64編碼Java字符串? – dimo414

回答

1

這工作正常。

你只需要字節碼轉換成十六進制表示,

String encodeAsUcs2(String messageContent) throws UnsupportedEncodingException { 
    byte[] bytes = messageContent.getBytes("UTF-16BE"); 

    StringBuilder sb = new StringBuilder(); 
    for (byte b : bytes) { 
    sb.append(String.format("%02X", b)); 
    } 

    return sb.toString(); 
} 
1

代碼

String s = "子"; 
byte[] utf16encodedBytes = s.getBytes("UTF-16") 

會給你編碼爲uft16字節的字符串。

我覺得你在這裏感到困惑的是你編碼到Base64,它給出了這些字節ASCII爲/v9bUA ==。數字4E02是十六進制編碼。要看你的例子的十六進制編碼,你可以嘗試:

String hexEncodedString = DatatypeConverter.printHexBinary(utf16encodedBytes);