Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Byte Array to String and vice versa

Tags:

android

I am using the Android javax API to encrypt a string which returns a byte array which I again convert into String (purpose is to write to textfile later).

Now using this String, I convert to byte array to decrypt which returns another byte array which I convert again to String.

I could not get this to work. I narrowed down the issue to the string conversion to byte array portion. Because if i use the encrpted byte array to decrypt and then get the String it works.

Not sure what's the issue. I have used the following for the conversion:

String str;
Byte [] theByteArray = str.getBytes("UTF-8");
String val = new String (theByteArray , "UTF-8");

and 

Byte [] theByteArray = str.getBytes();
String val = new String (theByteArray);

What is the best way to convert from byte array to string and vice versa without losing anything?

like image 348
aandroidtest Avatar asked May 23 '26 18:05

aandroidtest


1 Answers

You can use apache library's Hex class. It provides decode and encode functions.

String s = "42Gears Mobility Systems";
byte[] bytes = Hex.decodeHex(s.toCharArray());

String s2 = new String(Hex.encodeHex(bytes));
like image 61
PC. Avatar answered May 26 '26 11:05

PC.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!