将string转换为字节数组,然后返回到原始string

是否可以将string转换为字节数组,然后将其转换回Java或Android中的原始string?

我的目标是发送一些string到微控制器(Arduino),并将其存储到EEPROM(只有1 KB)。 我试图使用MD5哈希,但它似乎只是一种单向encryption。 我能做些什么来处理这个问题?

我会build议使用string的成员,但用一个明确的编码

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

通过使用明确的编码(以及支持所有Unicode的编码),可以避免仅调用text.getBytes()等问题:

  • 您明确地使用特定的编码,以便您知道以后使用哪种编码,而不是依赖平台默认值。
  • 你知道它将支持所有的Unicode(而不是像ISO-Latin-1)。

编辑:即使UTF-8是Android上的默认编码,我一定会明确这一点。 例如,这个问题只说“在Java或Android” – 所以这是完全可能的代码将最终被用于其他平台上。

基本上考虑到普通的Java平台可以有不同的默认编码,我认为最好是绝对明确的。 我已经看到太多的人使用默认编码和丢失数据来承担风险。

编辑:在我匆忙,我忘了提及,你不必使用编码的名称 – 你可以使用一个Charset来代替。 使用番石榴我真的使用:

 byte[] bytes = text.getBytes(Charsets.UTF_8); String text = new String(bytes, Charsets.UTF_8); 

你可以这样做。

string到字节数组

 String stringToConvert = "This String is 76 characters long and will be converted to an array of bytes"; byte[] theByteArray = stringToConvert.getBytes(); 

http://www.javadb.com/convert-string-to-byte-array

字节数组到string

 byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46}; String value = new String(byteArray); 

http://www.javadb.com/convert-byte-array-to-string

使用[String.getBytes()][1]转换为字节,并使用[String(byte[] data)][2]构造函数转换回string。

看看这个,你可以使用Base85: Base85 aka ASCII85 java项目

有同样的问题。

import java.io.FileInputStream; import java.io.ByteArrayOutputStream;

公共类FileHashStream {/ /写一个新的方法,将提供一个新的字节数组,并通常从inputstream中读取

 public static byte[] read(InputStream is) throws Exception { String path = /* type in the absolute path for the 'commons-codec-1.10-bin.zip' */; // must need a Byte buffer byte[] buf = new byte[1024 * 16] // we will use 16 kilobytes int len = 0; // we need a new input stream FileInputStream is = new FileInputStream(path); // use the buffer to update our "MessageDigest" instance while(true) { len = is.read(buf); if(len < 0) break; md.update(buf, 0, len); } // close the input stream is.close(); // call the "digest" method for obtaining the final hash-result byte[] ret = md.digest(); System.out.println("Length of Hash: " + ret.length); for(byte b : ret) { System.out.println(b + ", "); } String compare = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"; String verification = Hex.encodeHexString(ret); System.out.println(); System.out.println("===") System.out.println(verification); System.out.println("Equals? " + verification.equals(compare)); } 

}