将字符串转换为字节数组,然后返回原始字符串 [英] Convert a String to a byte array and then back to the original String
问题描述
是否可以在Java或Android中将字符串转换为字节数组,然后再转换回原始字符串?
Is it possible to convert a string to a 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 the only 1 KB). I tried to use an MD5 hash, but it seems it's only 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");
通过使用显式编码(并且支持所有 Unicode),您可以避免仅调用 text.getBytes()
等的问题:
By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes()
etc:
- 您明确使用了特定编码,因此您知道以后要使用哪种编码,而不是依赖于平台默认值.
- 您知道它将支持所有 Unicode(而不是 ISO-Latin-1).
尽管 UTF-8 是 Android 上的默认编码,但我肯定会明确说明这一点.例如,这个问题只说在 Java 或 Android 中"——所以完全有可能代码最终会在其他平台上使用.
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.
在我匆忙中,我忘了提到您不必使用编码的 name - 您可以使用 Charset
代替.使用 Guava 我真的会使用:
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);
这篇关于将字符串转换为字节数组,然后返回原始字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!