java charset decode issue in converting string to hex code

Viewed 4428

I read a string of bytes and I want to convert it to hex code. I know the general data is :

aa 01 00 1c 1e 38 5a 19 26 fc 00 7a e1 48 00 00 ff bf 00 58 01 2c 00 00 00 64 25 ff

I convert the string to hex using the following code:

 byte[] temp = record.value().getBytes();
                    StringBuffer result = new StringBuffer();
                    for (byte b : temp) {
                        result.append(String.format("%02X ", b));
                        result.append(" "); // delimiter
                    }
                    System.out.println(result);

and the output is :

EF BF BD 01 00 1C 1E 39 5A 18 40 EF BF BD 00 38 51 EF BF BD 00 00 EF BF BD EF BF BD 00 48 00 EF BF BD 00 00 00 64 EF BF BD 1F

The issue is it changed aa byte with EF BF BD.

So I tried applying Unicodes like the following:

byte[] temp = record.value().getBytes(StandardCharsets.ISO_8859_1);

or

byte[] temp = record.value().getBytes("windows-1252");

and the output changes to:

3F 01 00 1C 1E 39 5A 18 40 3F 00 38 51 3F 00 00 3F 3F 00 48 00 3F 00 00 00 64 3F 1F

this time it changed aa to 3F.

How can I fix this issue and print data correctly?

Note: having the same problem in C++, changing data from char[] to unsigned char[] solved the problem.

2 Answers

I tried your code and it works fine:

public class T14ReadBytes {
    public static void main(String[] args) {
        byte[] temp = new byte[10];
        temp[0] = (byte) 0xaa;
        temp[1] = (byte) 0x01;
        temp[2] = (byte) 0x00;
        temp[3] = (byte) 0x1c;
        temp[4] = (byte) 0x1e;
        temp[5] = (byte) 0x38;
        temp[6] = (byte) 0x5a;
        temp[7] = (byte) 0x19;
        temp[8] = (byte) 0x26;
        temp[9] = (byte) 0xfc;

        StringBuffer result = new StringBuffer();
        for (byte b : temp) {
            result.append(String.format("%02X ", b));
        }
        System.out.println(result);
    }
}

The result is: AA 01 00 1C 1E 38 5A 19 26 FC

Related