String str = "你好吗";
System.out.println(str);
String str1 = new String(str.getBytes("utf8"));
System.out.println(str1); str1 = new String(str1.getBytes("GBK"));
System.out.println(str1);你好吗
浣犲ソ鍚
娴g姴銈介崥锟�疑问:汉字转成了UTF8,怎么转不回来了啊??
另外我是要把中文STRING转成UTF8然后发给PYTHON.
用JAVA把中文"你好吗"转成UTF8是:浣犲ソ鍚
变成十六进制是:\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90
用PYTHON把中文"你好吗"转成UTF8是:'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97'
为什么会不一样呢?好奇怪.请朋友和前辈们帮看一下啊.快崩溃了..
UTF-8 每个汉字是3个字节,你转的少了一个,是你代码的问题。看我的代码
public static void main(String args[]) throws UnsupportedEncodingException {
String str = "你好吗";
System.out.println(str);
byte[] bs = str.getBytes("utf-8");
System.out.println(bs.length);
String str1 = new String(bs);
System.out.println(str1);
str1 = new String(str1.getBytes(),"utf-8");
System.out.println(str1);
str1 = new String(bs,"utf-8");
System.out.println(str1);
}三个汉字转为byte是9个,你又非得重新组合成unicode的字符串,2个算1个,等于4个字符,无形中丢了一个啦!
String str = "你好吗吗";
双数的字符,看得就更清楚了。 真凑巧,双数转化后为12个字节,拼成了6个字符。你再转回去依然是对的。哈哈! 不过可不能这么干哦!
使用的是平台默认的charset来解码String str1 = new String(str1.getBytes("utf8"),"utf-8");
手工指定解码方式汉字就不乱码了
public static String byteToString(byte[] bs) {
byte high, low;
byte maskHigh = (byte) 0xf0;
byte maskLow = 0x0f;
StringBuffer buf = new StringBuffer();
for (byte b : bs) {
high = (byte) ((b & maskHigh) >> 4);
low = (byte) (b & maskLow);
buf.append(findHex(high));
buf.append(findHex(low));
}
return buf.toString();
}