3

While converting ASCII String to EBCDIC:

System.out.println(new String("0810C2200000820000000400000000000000052852304131419391011590620022300270".getBytes("UTF-8"), "CP1047"));

I am getting below as output String:

ä??????

But, what I want is:

F0 F8    F1 F0    C2 20    00 00    82 00    00 00    04 00  00 00    00 00    00 00   F4 F1    F0 F1    F1 F5  F9 F0    F6 F2    F0 F0    F2 F2    F3 F0    F0 F2    F7 F0

How I can achieve it? Any help will be appreciated.

Thanks

Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108
  • is the formatting important? or do you want to output the bytes as text encoded in cp1047? – thst Apr 17 '15 at 06:04
  • You're decoding *from* CP1047 *to* UTF-16 with this code. The result of converting to EBCDIC is a byte array, not a String. – user207421 Apr 17 '15 at 06:56

1 Answers1

5

You can convert the string this way

String string = "0810C220";
byte[] bytes = string.getBytes("CP1047");
for (int i = 0; i < bytes.length; i++) {
    System.out.printf("%s %X%n", string.charAt(i), bytes[i]);
}

But your example seems to be wrong.

following are correct, one character from input string is converted to the related EBCDIC code

0 F0
8 F8
1 F1
0 F0

here your example is wrong, because your example treats C2 and 20 as two characters in the input string but not as two characters in the EBCDIC code

C C3
2 F2
2 F2
0 F0

For the conversion in the other direction you could do it that way

// string with hexadecimal EBCDIC codes
String sb = "F0F8F1F0";
int countOfHexValues = sb.length() / 2;
byte[] bytes = new byte[countOfHexValues];
for(int i = 0; i < countOfHexValues; i++) {
    int hexValueIndex = i * 2;
    // take one hexadecimal string value
    String hexValue = sb.substring(hexValueIndex, hexValueIndex + 2);
    // convert it to a byte
    bytes[i] = (byte) (Integer.parseInt(hexValue, 16) & 0xFF);
}
// constructs a String by decoding bytes as EBCDIC
String string = new String(bytes, "CP1047");
SubOptimal
  • 22,518
  • 3
  • 53
  • 69
  • How Can I achieve reverse of it, means from a String str="F0F8F1F0" to 0810? – Arpit Aggarwal Apr 17 '15 at 10:10
  • Thank you, it's of great help!! – Arpit Aggarwal Apr 17 '15 at 10:32
  • I am facing another issue with conversion from hex to ascii, that is it is giving me corrupt data for some hex values, might be for postive hex. can you please tell me how can I fix it? – Arpit Aggarwal Apr 21 '15 at 13:43
  • like this : 000086^Ìb* – Arpit Aggarwal Apr 21 '15 at 13:44
  • What have you tried? What is the hex string you want to convert into ASCII? – SubOptimal Apr 21 '15 at 15:13
  • If you want to convert EBCDIC (as hex code string. e.g. "F0F1F0F0767F46") into ASCII you should use `new String(bytes, "ASCII")` instead of `new String(bytes, "CP1047")`. As you might know what the EBCDIC is look it have a look at the convertion page in the [Wikipedia](https://en.wikipedia.org/wiki/EBCDIC_1047) to find the right character translation. – SubOptimal Apr 22 '15 at 06:09