在Java或Android中,将字符串转换为字节数组,然后将其转换回原始字符串是否可能?
我的目标是将一些字符串发送到微控制器(Arduino)并将其存储到EEPROM中(仅为1 KB)。我尝试使用MD5哈希,但似乎它只是单向加密。我应该怎么处理这个问题?
我建议使用字符串的成员,但需要显式指定编码:
byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");
text.getBytes()
等的问题:
byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);
你可以这样做。
字符串转字节数组
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
将字节数组转换为字符串
byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
String value = new String(byteArray);
:将字节数组转换为字符串。[String.getBytes()][1]
将其转换为字节数组,然后使用 [String(byte[] data)][2]
构造函数将其转换回字符串。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
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));
}
}
byte [] pdfBytes = Base64.decode(myPdfBase64String,Base64.DEFAULT)