2013-10-15 78 views
4

我試圖將字節[]轉換爲字符串,並將字符串轉換爲字節[]。我回顧不是相同的byte []數組。字節數組 - >字符串 - >字節數組

byte[] bArray1 = myFunction(); 
System.out.println("array1 = " + bArray1.toString()); 
String str = new String(bArray1); 
byte[] bArray2 = str.getBytes(); 
System.out.println("array2 = " + bArray2.toString()); 

執行後我得到:

array1 = [-15, -87, -44, 61, -115, 23, -3, 75, 99, 36, -49, 21, -41, -63, 100, -49] 
array2 = [-17, -65, -67, -17, -65, -67, 61, -17, -65, -67, 23, -17, -65, -67, 75, 99, 36, -17, -65, -67, 21, -17, -65, -67, -17, -65, -67, 100, -17, -65, -67, -17, -65, -67] 

它爲什麼會發生,我怎麼能得到相同的陣列?

我的電腦上這項工作,但不能在我的Android:

byte[] bArray1 = myFunction(); 
String str = Base64.encodeToString(bArray1, Base64.DEFAULT); 
byte[] bArray2 = Base64.decode(str, Base64.DEFAULT); 

我所看到的文章Hex-encoded String to Byte Array。 但android沒有class Hex。

編輯

對不起,我錯了是Base64是行不通的。

這在安卓2.3.3,2.3.4,4.2,4.3進行了測試,它的工作原理:

byte[] bArray1 = myFunction(); 
String str = Base64.encodeToString(bArray1, Base64.DEFAULT); 
byte[] bArray2 = Base64.decode(str, Base64.DEFAULT); 
+0

它們是相同的不同的字符編碼字符串 – tom

+0

建立在湯姆的評論,你在處理從myFunction()返回的byte []中的實際ASCII /可打印數據?你想通過轉換來做什麼? –

+2

[String to Byte Array]的可能重複(http://stackoverflow.com/questions/6650650/string-to-byte-array) – alfasin

回答

0

您應該能夠通過使用ByteBufferCharSet來解決這個問題。

默認情況下,Android使用UTF-8編碼(您可以使用Charset.defaultCharset()進行檢查),因此您需要指定如何編碼和解碼字符串。

ByteBuffer buff = Charset.defaultCharset().encode(myString); 
byte[] bytes = buff.array(); 
CharBuffer charBuff = Charset.defaultCharset().decode(bytes); 
String original = charBuff.toString(); 

這應該有效。

0

實例這個功能可能會幫助你

將字符串轉換爲字節數組

public static byte[] convertStirngToByteArray(String s) 
{ 
byte[] byteArray = null; 
if(s!=null) 
{ 
if(s.length()>0) 
{ 
try 
{ 
    byteArray = s.getBytes(); 
} catch (Exception e) 
{ 
e.printStackTrace(); 
} 
} 
} 
return byteArray; 
} 

轉換字節數組字符串

public static String convertByteArrayToString(byte[] byteArray) 
{ 
String s = null; 
if(byteArray!=null) 
{ 
if(byteArray.length>0) 
{ 
try 
{ 
    s = new String(byteArray,"UTF-8"); 
} 
catch (Exception e) 
{ 
e.printStackTrace(); 
} 
} 
} 
return s; 
}