0

I'm working on a project in Java. I used cipher to encode and decode. Cipher returns me a byte array. For some reasons I have to send this byte array in String Do you have any ideas on how can I get back the same byte array?

For example, if I had the String:

"[B@5024d44"

and I want to convert into byte[] but I want the byte[] to be equals to [B@5024d44. Is it possible?

Thanks for your answers.

skydooo
  • 1
  • 1

2 Answers2

2

[B@5024d44 tells you you have a byte array, and tells you nothing whatsoever about what is in it. You cannot convert that back to anything meaningful.

To convert a byte array to a String reversibly, use Base64.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

If you have a string [B@5024d44, you can convert it to a byte[] array, and then convert this array back to a string. These two strings would be equal, but the array wouldn't be equal to the string, and also the contents of the array wouldn't be equal to the string:

String str = "[B@5024d44";
byte[] arr = str.getBytes(StandardCharsets.UTF_8);
String str1 = new String(arr, StandardCharsets.UTF_8);

// strings are equal
System.out.println(str.equals(str1)); // true

// string representation of the array
System.out.println(arr); // [B@5451c3a8

// contents of the array
System.out.println(Arrays.toString(arr));
// [91, 66, 64, 53, 48, 50, 52, 100, 52, 52]

See also: How can I convert a string into a GZIP Base64 string?