javac#.netbytecharset

Convert a byte array from one encoding to another java


hi guys i should convert this code to C# in Java. Could you give me a hand?

private static String ConvertStringToHexStringByteArray(String input) {
        Encoding ebcdic = Encoding.GetEncoding("IBM037");
        Encoding utf8 = Encoding.UTF8;
        byte[] utfBytes = utf8.GetBytes(input);
        byte[] isoBytes = Encoding.Convert(utf8, ebcdic, utfBytes);
        StringBuilder hex = new StringBuilder(isoBytes.length * 2);
        foreach( byte b in isoBytes)
        hex.AppendFormat("{0:x2}", b);
        return hex.ToString();

    }

I tried to convert it to java like this. But the result is different:

private static String ConvertStringToHexStringByteArray(String input) throws UnsupportedEncodingException {

        byte[] isoBytes = input.getBytes("IBM037");
        StringBuilder hex = new StringBuilder(isoBytes.length * 2);

        for (byte b : isoBytes) {
            hex.append(String.format("%02x", b));
        }
        return hex.toString();

    }

input = "X1GRUPPO 00000000726272772"
expected = "e7f1c7d9e4d7d7d64040404040f0f0f0f0f0f0f0f0f1f6f7f3f5f3f5f5f2"
result = "e7f1c7d9e4d7d7d640f0f0f0f0f0f0f0f0f7f2f6f2f7f2f7f7f2"

what am I doing wrong?


Solution

  • Your code works but you are comparing the output for two different input strings.

    When you write expected and result side by side:

    e7f1c7d9e4d7d7d64040404040f0f0f0f0f0f0f0f0f1f6f7f3f5f3f5f5f2
    e7f1c7d9e4d7d7d640f0f0f0f0f0f0f0f0f7f2f6f2f7f2f7f7f2
    

    you will notice that both start with the same sequence (e7f1c7d9e4d7d7d6) which seems to come from a common beginning X1GRUPPO

    But then the two outputs differ:

    4040404040f0f0f0f0f0f0f0f0f1f6f7f3f5f3f5f5f2
    40f0f0f0f0f0f0f0f0f7f2f6f2f7f2f7f7f2
    

    Reasoning from the input that you provided, the remainder of first input string starts with 5 spaces followed by "00000000167353552"

    This means the complete input for the C# code was "X1GRUPPO 00000000167353552", which is not the same input that you provided to the Java code and then clearly the output cannot match.