中文例子:嘻嘻哈哈笑翻天
函数:
private String convertStringToUCS2(String inString) {//throws UnsupportedEncodingException{
try{
byte[] tmp = inString.getBytes("GBK"); String temp = new String(tmp,"gb2312");
int tempLen = temp.length();
byte retBytes[] = new byte[tempLen * 2];
int charVal = 0;
for(int i = 0;i < tempLen; i++) {
charVal = temp.charAt(i); retBytes[2 * i] = (byte)(0xff & charVal);
retBytes[2 * i + 1] = (byte)((0xff00 & charVal) >> 8); } return new String(retBytes);
}catch(UnsupportedEncodingException ueex){
//poplog.error(ueex.toString());
return null;
}
}
前面几个字是可以转换的,但是后面的“翻天”两个字不能正确转换,出来的是问号,编码为3F,急
函数:
private String convertStringToUCS2(String inString) {//throws UnsupportedEncodingException{
try{
byte[] tmp = inString.getBytes("GBK"); String temp = new String(tmp,"gb2312");
int tempLen = temp.length();
byte retBytes[] = new byte[tempLen * 2];
int charVal = 0;
for(int i = 0;i < tempLen; i++) {
charVal = temp.charAt(i); retBytes[2 * i] = (byte)(0xff & charVal);
retBytes[2 * i + 1] = (byte)((0xff00 & charVal) >> 8); } return new String(retBytes);
}catch(UnsupportedEncodingException ueex){
//poplog.error(ueex.toString());
return null;
}
}
前面几个字是可以转换的,但是后面的“翻天”两个字不能正确转换,出来的是问号,编码为3F,急
{
charVal = temp.charAt(i);
retBytes[2 * i] = (byte) (0xff & charVal);
retBytes[2 * i + 1] = (byte) ((0xff00 & charVal) >> 8);
}
这个地方主要是获取汉字的10进制unicode码,中文最终传输的格式是unicode 16进制的,但是显示的是乱码
to wifewifewife:
这个转换完之后是汉字的双字节,输出为乱码,但是实际传输的是unicode 16进制码
你这temp不是和传进的参数一样了?这两句话有什么用。return new String(retBytes);
这应该也是按GBK编码把字节转成字符串。
还要注意字节序, 可以自己在retBytes前面加上两个字节,-1 -2 或者-2 -1调整,也可以改变你这两个的顺序。
retBytes[2 * i] = (byte)(0xff & charVal);
retBytes[2 * i + 1] = (byte)((0xff00 & charVal) >> 8);
换成:
retBytes[2 * i+1] = (byte)(0xff & charVal);
retBytes[2 * i] = (byte)((0xff00 & charVal) >> 8);