![](/img/trans.png)
[英]Java byte array doesn't convert back to its original string when using DatatypeConverter
[英]Convert a String to a byte array and then back to the original String
是否可以將字符串轉換為字節數組,然后將其轉換回 Java 或 Android 中的原始字符串?
我的目標是將一些字符串發送到微控制器(Arduino)並將其存儲到 EEPROM(這是唯一的 1 KB)中。 我嘗試使用MD5哈希,但它似乎只是單向加密。 我能做些什么來處理這個問題?
我建議使用字符串的成員,但使用顯式編碼:
byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");
通過使用顯式編碼(以及支持所有 Unicode 的編碼),您可以避免僅調用text.getBytes()
等的問題:
編輯:盡管 UTF-8 是 Android 上的默認編碼,但我肯定會明確指出這一點。 例如,這個問題只說“在 Java 或 Android 中”——所以完全有可能代碼最終會在其他平台上使用。
基本上考慮到普通的 Java 平台可以有不同的默認編碼,我認為最好是絕對明確的。 我見過太多人使用默認編碼並丟失數據來承擔這種風險。
編輯:在我匆忙中,我忘了提到您不必使用編碼的名稱- 您可以使用Charset
代替。 使用番石榴我真的會使用:
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]
構造函數轉換回字符串。
看看這個,你可以使用Base85: Base85又名ASCII85 java項目
有同樣的問題。
導入 java.io.FileInputStream; 導入 java.io.ByteArrayOutputStream;
public class FileHashStream { // 編寫一個新方法,該方法將提供一個新的 Byte 數組,並且通常從輸入流中讀取
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.