Sreemanth Jasti
Sreemanth Jasti

Reputation: 95

Printing byte array containing EBCDIC values doesnt give expected value

I created a string converted got a byte array using EBCDIC encoding from it. When I printed the array the value of H it is not the same found in EBCDIC chart.

Expected output

EBCDIC Value for "H"-->200 as per link EBCDIC 1047 chart

Actual output

EBCDIC Value for "H"-->[-56]

public static void main(String[] args) throws UnsupportedEncodingException {
    String str = "H";
    byte[] b1 = new byte[10];
    b1 = str.getBytes("Cp1047");
    System.out.println(Arrays.toString(b1));

    for (byte b : b1) {
        System.out.println(b);
    }

    b1 = str.getBytes("UTF-16");
    System.out.println(Arrays.toString(b1));

    b1 = str.getBytes();
    System.out.println(Arrays.toString(b1));
}

Upvotes: 0

Views: 843

Answers (1)

JJF
JJF

Reputation: 2777

In your loop

for (byte b : b1)
   System.out.println(b);  

Java is sign extending b (a byte) when it promotes it to an integer which results in the value of 0xFFFFFFC8 being printed. 0xFFFFFFC8 is the two's complement representation of the signed number -56. See this. You can prevent the sign extension by doing this:

for (byte b  :b1)
  System.out.println(b & 0xFF);  

This will cause the value 0xC8 (200 in decimal) to get printed.

Upvotes: 4

Related Questions