4

I'm trying to convert byte[] to String and than String to byte[]. I retrive not the same byte[] array.

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

After executing i get:

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]

Why does it happen and how can i get the same array?

This work on my computer, but not on my android:

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

I have seen the article Hex-encoded String to Byte Array. But android have not class Hex.

Edited

I'm sorry, i was wrong that Base64 is not working.

This was tested at android 2.3.3, 2.3.4, 4.2, 4.3 and it works:

byte[] bArray1 = myFunction();
String str = Base64.encodeToString(bArray1, Base64.DEFAULT);
byte[] bArray2 = Base64.decode(str, Base64.DEFAULT);
Community
  • 1
  • 1
user2883335
  • 76
  • 1
  • 6
  • they are different character encodings of the same string – tom Oct 15 '13 at 18:02
  • Building on tom's comment, are you dealing with actual ASCII/printable data in the byte[] returned from myFunction() ? And what are you trying to do by the conversion ? – K5 User Oct 15 '13 at 18:09
  • 2
    possible duplicate of [String to Byte Array](http://stackoverflow.com/questions/6650650/string-to-byte-array) – Nir Alfasi Oct 15 '13 at 18:25
  • another solution: http://stackoverflow.com/a/14669835/1057429 – Nir Alfasi Oct 15 '13 at 18:27

2 Answers2

0

You should be able to solve this by using a ByteBuffer and a CharSet.

Android uses UTF-8 encoding by default (You can check this with Charset.defaultCharset()), so you need to specify that that is how you want to encode and decode your strings.

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

This should work.

Codeman
  • 12,157
  • 10
  • 53
  • 91
0

Example this function might be help you

Converting string to byte array

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;
}

Converting byte array to string

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;
}
Parth Akbari
  • 641
  • 7
  • 24