Is it possible to convert a string to byte array and then convert it back to the original string in Java or Android?
My objective is to send some strings to a microcontroller (Arduino) and store it into EEPROM (which is only 1 KB). I tried to use an MD5 hash, but it seems it's only a one way encryption. What can I do to deal with this issue?
I would suggest using the members of string, but with an explicit encoding:
By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling
text.getBytes()
etc:EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.
Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.
EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a
Charset
instead. Using Guava I'd really use:Check out this, you can use Base85: Base85 aka ASCII85 java projects
Had the same question.
You can do it like this.
String to byte array
http://www.javadb.com/convert-string-to-byte-array
Byte array to String
http://www.javadb.com/convert-byte-array-to-string
import java.io.FileInputStream; import java.io.ByteArrayOutputStream;
public class FileHashStream { // write a new method that will provide a new Byte array, and where this generally reads from an input stream
}
Use
[String.getBytes()][1]
to convert to bytes and use[String(byte[] data)][2]
constructor to convert back to string.