2015-11-02 43 views
2

我使用字符串進行字節數組傳輸,但發現有些奇怪的東西。有人可以解釋,爲什麼會發生這種情況?在字符串換行後字節不相等

byte[] bytes1 = new byte[]{-104, 73, 61, -15, -92, 109, 62, -99, 50, 82, 26, 87, 38, 110, -12, 49, -104, 73, 61, -15, -92, 109, 62, -99}; 
byte[] bytes2 = new String(bytes1).getBytes(); 
//for now bytes2 is equal to: {63, 73, 61, -15, -92, 109, 62, -99, 50, 82, 26, 87, 38, 110, -12, 49, 63, 73, 61, -15, -92, 109, 62, -99} 
System.out.println(Arrays.equals(bytes1, bytes2));//false 
for(int i = 0; i < bytes2.length; i++){ 
    if(bytes2[i] == 63) { 
     bytes2[i] = -104; 
    } 
} 
System.out.println(Arrays.equals(bytes1, bytes2));//true 

ps bytes1 - 這是triple des secret key bytes數組。每次它不同,但只有在案例中,如果bytes1包含-104值,它纔會失敗。非常感謝。

+1

請說出你希望這段代碼輸出什麼,以及它輸出什麼。 「奇怪的東西」不是一個特定的錯誤。 –

+0

我在'System.out.println'行添加註釋 – degr

+0

我得到虛假的錯誤檢查它在這裏https://ideone.com/zpPHNg – SpringLearner

回答

6

字符串不是字節數組,字節數組不是字符串。你不能用一個直接轉移另一個。

字符串在邏輯上是char數組。如果你想在字符和字節之間轉換,你需要一個字符編碼,它指定從字符到字節的映射,反之亦然。

您在這裏遇到的問題是您正在使用JVM的默認字符編碼,並嘗試轉換該編碼中不支持的字節值。

如果你必須在字符串中存儲一個字節數組,你應該先做一些像base64編碼的東西。

+0

這工作byte [] bytes2 = Base64.getDecoder()。decode (new String(Base64.getEncoder()。encode(bytes1))); – degr