我有一個大小爲8的字節數組。 我使用下面的代碼將其轉換爲字符串。 (見下文)。Probem與java,String.getBytes方法
現在,當我使用getBytes方法將字符串再次轉換爲byte []時,結果是荒謬的,這是一個16字節的字節[],與前一個字節數組只有少數(2或3)匹配字節。有人能告訴我我要去哪裏嗎?
byte[] message = new byte[8];
//initialize message
printBytes("message: " + message.length + " = ", message);
try {
String test = new String(message, "utf-8");
System.out.println(test);
byte[] f = test.getBytes("utf-8");
Help.printBytes("test = " + f.length, f);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
printBytes功能:
public static void printBytes(String msg, byte[] b){
System.out.print(msg + " = ");
for(int i = 0; i < b.length; i++){
System.out.print("" + String.format("%02X", b[i]));
}
System.out.println("\n");
}
輸出:
message: 8 = = 9A52D5D6C6E999AD
�R���陭
test = 16 = EFBFBD52EFBFBDEFBFBDEFBFBDE999AD
由於字符串編碼Java使用不是8位,它的16位。可能是UNICODE或UTF。不知道哪個。 –
此外,我不認爲將字節數組轉換爲字符串是一個好主意,如果你想它被重現爲字節數組。您可以嘗試轉換爲十六進制字符串。 –
但是在做相反的事情時,它也應該使用相同的編碼。無論如何,我應該得到預期的結果。 – vish4071