2009-05-21 97 views
3

做工精細我初始化這樣的字節數組:字節[]到字符串字節數組轉換並沒有在Java

public static byte[] tmpIV = {0x43, (byte)0x6d, 0x22, (byte)0x9a, 0x22, 
         (byte)0xf8, (byte)0xcf, (byte)0xfe, 0x15, 0x21, 
         (byte)0x0b, 0x38, 0x01, (byte)0xa7, (byte)0xfc, 0x0e}; 

如果我打印出來它給了我

67 109 34  -102  34  -8   -49  -2  21  33 
11 56 1  -89  -4  14 

然後我將整個字節數組轉換爲字符串併發送給我的朋友。

String str = new String(tmpIV); 

我的朋友是一個C#程序員

所以我的朋友得到一些其他數據。我的朋友將如何獲得我發送的相同數據。 同樣在Java中,如果我再改上面的字符串轉換成字節數組,我沒有得到我傳一個確切:

67  109  34  -17  -65  -67  34  -17  -65  -67 
-17  -65  -67  -17   -65 -67  21  33 11  56  1 
-17  -65  -67   -17  -65  -67 

回答

12

的問題是,你已經轉換的字節數組到平臺默認的字符串編碼。

如果這是任意的二進制數據(這似乎是),那麼你不應該使用任何正常字符編碼將其轉換成字符串 - 使用的base64來代替。

從Java使用base64不是,特別是很容易(因爲它不在標準庫AFAIK中),但是可以使用各種第三方庫,例如the one in the Apache Commons Codec library

在C#側這將是一個更容易 - 只需使用:

byte[] data = Convert.FromBase64String(text); 
-4

我同意前面的答案 - 你應該使用的base64的方法,但是使用Base64很容易)。只要使用的base64 UTIL類從sun.misc包:

import sun.misc.BASE64Decoder; 
import sun.misc.BASE64Encoder; 
import java.io.IOException; 
import java.util.Arrays; 
public class Base64Test { 

    public static byte[] tmpIV = {0x43, (byte) 0x6d, 0x22, (byte) 0x9a, 0x22, 
      (byte) 0xf8, (byte) 0xcf, (byte) 0xfe, 0x15, 0x21, 
      (byte) 0x0b, 0x38, 0x01, (byte) 0xa7, (byte) 0xfc, 0x0e}; 


    public static void main(String[] args) { 
     try { 
      String encoded = new BASE64Encoder().encode(tmpIV); 
      System.out.println(encoded); 
      byte[] decoded = new BASE64Decoder().decodeBuffer(encoded); 
      System.out.println(Arrays.equals(tmpIV,decoded)); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+4

請勿使用非標準API的類! – 2009-05-21 10:16:41

0

你必須確保你和你的朋友使用相同的編碼協議。因此,在Java方面,而不是String aString = new String(byteArray)最好使用String aString = new String(byteArray, Charset.forName("UTF-8"))(例如,如果你們兩個都比較喜歡「UTF-8」)

PS:順便說一句,你可能發現你朋友的字節數組幾次有以下模式「-17 -65 -67」。根據我的經驗,這三個數字模式的意思是「?」 UTF-8中的字符

相關問題