Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert String to byte array and vice versa in Java

I am trying to convert a byte array to String. But the conversion alter the values. That means I cannot restore the byte array from the converted String.

byte[] array = {-64,-88,1,-2};
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(array);
String result = out.toString("UTF-8");
byte[] array2 = result.getBytes("UTF-8");
// output of array2: {-17,-65,-67,-17}
like image 797
shantanu Avatar asked Dec 07 '25 10:12

shantanu


1 Answers

It's a charset issue - utf-8 has more than 1 byte per char. Try the same with some 1-byte charset like

String result = out.toString("ISO-8859-15");
byte[] array2 = result.getBytes("ISO-8859-15");
like image 107
Jan Avatar answered Dec 10 '25 04:12

Jan



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!