一个字符串转换为字节数组,然后返回到原始字符串字符串、数组、转换为、字节

2023-09-05 10:14:35 作者:体会心痛

是否有可能将字符串转换为字节数组,然后将其转换回用Java或者Android原始字符串?

Is it possible to convert a string to byte array and then convert it back to the original string in Java or Android?

我的目标是一些字符串发送到微控制器(Arduino的),​​并将其存储到EEPROM(这是只有1  KB)。我试图用一个 MD5哈希的,但现在看来,这只是一个单向加密。我能做些什么来解决这个问题?

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:

byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");

使用显式编码(和一个支持所有的统一code)避免只调用的问题 text.getBytes()

您正在明确使用特定编码,所以你知道以后要使用的编码,而不是依赖于平台的默认值。 您知道它会支持所有的Uni code(而不是,比方说,ISO-Latin-1的)。

编辑:尽管UTF-8是在Android的默认编码,我肯定会明确这一点。例如,这个问题只能说用Java或者Android - 因此它完全有可能在code最终会在其他平台上使用

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.

基本上考虑到正常的Java平台的可以的具有不同的默认编码,我认为这是最好是绝对明确的。我见过太多的人在使用默认的编码和数据丢失承担这个风险。

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.

编辑:在我的匆忙我忘了提,你没有使用的编码的名称的 - 你可以用字符集而不是。使用番石榴我会的真正的使用:

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:

byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);
 
精彩推荐
图片推荐