【发布时间】:2015-10-15 04:54:39
【问题描述】:
考虑以下几点:
public static void main(String... strings) throws Exception {
byte[] b = { -30, -128, -94 };
//section utf-32
String string1 = new String(b,"UTF-32");
System.out.println(string1); //prints ?
printBytes(string1.getBytes("UTF-32")); //prints 0 0 -1 -3
printBytes(string1.getBytes()); //prints 63
//section utf-8
String string2 = new String(b,"UTF-8");
System.out.println(string2); // prints •
printBytes(string2.getBytes("UTF-8")); //prints -30 -128 -94
printBytes(string2.getBytes()); //prints -107
}
public static void printBytes(byte[] bytes){
for(byte b : bytes){
System.out.print(b + " " );
}
System.out.println();
}
输出:
?
0 0 -1 -3
63
•
-30 -128 -94
-107
所以我有两个问题:
- 在两个部分中:为什么输出
getBytes()和getBytes(charSet)是不同的,即使我已经特别提到了字符串的字符集 - 为什么 utf-32 部分中
getByte的两个字节输出与实际的byte[] b不同? (即如何将字符串转换回其原始字节数组?)
【问题讨论】:
标签: java utf-8 character-encoding utf-32