2
我有一個字節數組,並使用new String(array)
從它創建字符串。當我使用.getBytes()
將它轉換回字節數組時,它不會返回原始字節數組。是什麼賦予了?無法從字符串取回原始字節數組
String text = "two hats";
boolean t1 = Arrays.equals(text.getBytes(), text); // true
byte[] barray = {(byte)0x8f, (byte)0xd5, (byte)0xaf, (byte)0x30, (byte)0xb9};
String test1 = new String(barray);
boolean t2 = Arrays.equals(barray.getBytes(), test1); // false
// I tried setting an encoding but that didn't help.
Charset cs = Charset.forName("UTF-8");
String test2 = new String(barray, cs);
boolean t3 = Arrays.equals(barray, test2, cs); // false
這是我實際使用的代碼。
// test byte array vs string
public static void testEqual(byte[] bytes, String str) {
byte[] fromString = str.getBytes();
printBytes(bytes);
printBytes(fromString);
System.out.println(Arrays.equals(bytes, fromString));
}
// test byte array vs string, with charset
public static void testEqual(byte[] bytes, String str, Charset charset) {
byte[] fromString = str.getBytes(charset);
printBytes(bytes);
printBytes(fromString);
System.out.println(Arrays.equals(bytes, fromString));
}
// prints bytes as hex string
public static void printBytes(byte[] bytes) {
for (byte b: bytes) {
System.out.print(String.format("%02X ", b));
}
System.out.println();
}
public static void main(String[] args) {
String text = "two hats";
testEqual(text.getBytes(), text); // works fine
byte[] barray = {(byte)0x8f, (byte)0xd5, (byte)0xaf, (byte)0x30, (byte)0xb9};
String test1 = new String(barray); // breaks
testEqual(barray, test1);
Charset cs = Charset.forName("UTF-8"); // breaks too
String test2 = new String(barray, cs);
testEqual(barray, test2, cs);
}
PS:我不希望使用Base64編碼或諸如此類
爲什麼這是一個問題?我期望字符串本質上是一個字節數組。 – quantumSoup
@quantumSoup:他們不是。他們的序列*字符*。他們是*文本*數據。如果要將* binary *數據表示爲* text *,則需要執行適當的轉換。 –
我最初反對將它編碼爲文本,因爲它總是帶來一些開銷。像base64這樣的33%似乎是過度的。 – quantumSoup