简体   繁体   中英

Java String and byte[] conversion madness

How do I extract a byte[] from a String with the correct format/encoding?

This is what I have:

byte[] bytes = // some byte[] derived from custom code
String bytesString = // some string derived from the bytes above with custom code
byte[] newBytes = // TODO: transform bytesString back into bytes above

System.out.println(Arrays.toString(bytes));
// [74, -61, 58, 97, 127, -8, -5, -123, 70, 51, 65, 109, -20, -43, 117, 83]

System.out.println(bytesString);
// JÃ:aøû…F3AmìÕuS

System.out.println(Arrays.toString(bytesString.getBytes()));  // similar but not identical 
// [74, -61, -125, 58, 97, 127, -61, -72, -61, -69, -62, -123, 70, 51, 65, 109, -61, -84, -61, -107, 117, 83]

I am trying to transform the bytesString above back into the exact byte[] . This is the closest I've got:

byte[] newBytes = bytesString.getBytes("UTF-16LE");
System.out.println(newBytes);  // identical if we remove the 0s
// [74, 0, -61, 0, 58, 0, 97, 0, 127, 0, -8, 0, -5, 0, -123, 0, 70, 0, 51, 0, 65, 0, 109, 0, -20, 0, -43, 0, 117, 0, 83, 0]

Of course, I don't want to just remove the 0s from the array above. What am I missing?

Quick demo of proper using the charset when handling byte arrays and String:

byte[] arr = {74, -61, 58, 97, 127, -8, -5, -123, 70, 51, 65, 109, -20, -43, 117, 83};
String bytesString = new String(arr, "ISO-8859-1"); // or "UTF-16LE"
byte[] bbb = bytesString.getBytes("ISO-8859-1");    // or "UTF-16LE"

System.out.println("string     : '" + bytesString + "'");
System.out.println("input array: " + Arrays.toString(arr));
System.out.println("bytesString: " + Arrays.toString(bbb));

prints equal byte arrays:

string     : '썊愺藻㍆流헬卵'
input array: [74, -61, 58, 97, 127, -8, -5, -123, 70, 51, 65, 109, -20, -43, 117, 83]
bytesString: [74, -61, 58, 97, 127, -8, -5, -123, 70, 51, 65, 109, -20, -43, 117, 83]

Same result is printed if "UTF-16LE" charset is provided both when creating a string and getting bytes out of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM