0

In java,

// already set
byte[] bytes = ...;

byte array can be cast to string like

String s = bytes.toString();

The question is: how can I recover the same "bytes" from "s"?

the truth is that, the following code is wrong.

byte[] byteFromString = x.getBytes();
  • The answer to your question could depend on the _encoding_ which the string has. For example, in UTF-8, a character might consist of 4 bytes, but it could also consist of only one byte. – Tim Biegeleisen May 09 '16 at 15:33
  • 1
    http://stackoverflow.com/questions/19834854/how-to-cast-string-to-byte-array – ryekayo May 09 '16 at 15:34
  • Strictly speaking `String s = bytes.toString();` isn't a cast operation – Lee May 09 '16 at 15:40

1 Answers1

0

If you just used bytes.toString(), then no it's literally impossible. That gets you a string representing the hash code of the byte[], which is essentially random and bears no relationship to the actual contents of the byte[].

If the byte[] actually represented an encoding of a string, like UTF-8, then you can do new String(bytes, StandardCharsets.UTF_8) to convert it to a String, and string.getBytes(StandardCharsets.UTF_8) to convert it back.

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