疯狂的Java字符串和字节[]转换。

问题描述 投票:0回答:1

如何提取 byte[]String 用正确的格式编码?

这就是我的情况。

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]

我想把... bytesString 上回确切的 byte[]. 这是我得到的最接近的结果。

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]

当然,我不想只从上面的数组中去掉0号。我缺少了什么?

java arrays encoding endianness data-conversion
1个回答
2
投票

快速演示处理字节数组和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));

打印相等的字节数组。

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]

打印相同的结果,如果 "UTF-16LE" 在创建字符串和从字符串中获取字节时,都会提供charset。

© www.soinside.com 2019 - 2024. All rights reserved.