考虑以下:
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
?(即如何将字符串转换回其原始字节数组?)