Příklad

public static void main(String[] args){
byte[] bytes = {
(byte) 0xbc,
(byte) 0xf2,
(byte) 0xcc,
(byte) 0xe5,
(byte) 0xd6,
(byte) 0xd0,
(byte) 0xce,
(byte) 0xc4,
};
String str = new String(bytes);
for (int i = 0, n = str.length(); i < n ; i++) {
System.out.println("0x" + Integer.toHexString(str.charAt(i))); //$NON-NLS-1$
}
}
Řešení
Použijte jednu z následujících metod s parametrem znakové sady pro uvedení správné znakové sady.
  • java.lang.String.String (byte[], java.lang.String)
  • java.lang.String.String (byte[], int, int, java.lang.String)

public static void main(String[] args) {
byte[] bytes = {(byte) 0xbc, (byte) 0xf2, (byte) 0xcc, (byte) 0xe5,
(byte) 0xd6, (byte) 0xd0, (byte) 0xce, (byte) 0xc4,};
// GB18030.
String str = new String(bytes, "GB18030"); //$NON-NLS-1$

for (int i = 0, n = str.length(); i < n ; i++) {
System.out.println("0x" + Integer.toHexString(com.ibm.icu.text.UTF16.charAt(str, i))); //$NON-NLS-1$
}
}
Řešení
Použijte třídy v java.nio a java.nio.charset

public static void main(String[] args) {
byte[] bytes = {
(byte) 0xbc,
(byte) 0xf2,
(byte) 0xcc,
(byte) 0xe5,
(byte) 0xd6,
(byte) 0xd0,
(byte) 0xce,
(byte) 0xc4,
};

Charset cs = Charset.forName("GB18030"); //$NON-NLS-1$
CharsetDecoder decoder = cs.newDecoder();
CharBuffer cb = decoder.decode(ByteBuffer.wrap(bytes));
String str = cb.toString();

for (int i = 0, n = str.length(); i < n ; i++) {
System.out.println("0x" + Integer.toHexString(com.ibm.icu.text.UTF16.charAt(str, i))); //$NON-NLS-1$
}
}