简体   繁体   English

将字节数组从一种编码转换为另一种java

[英]Convert a byte array from one encoding to another java

hi guys i should convert this code to C# in Java.大家好,我应该将此代码转换为 Java 中的 C#。 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.我试图像这样将它转换为java。 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?我究竟做错了什么?

Your code works but you are comparing the output for two different input strings.您的代码有效,但您正在比较两个不同输入字符串的输出。

When you write expected and result side by side:当您并排编写expectedresult

e7f1c7d9e4d7d7d64040404040f0f0f0f0f0f0f0f0f1f6f7f3f5f3f5f5f2
e7f1c7d9e4d7d7d640f0f0f0f0f0f0f0f0f7f2f6f2f7f2f7f7f2

you will notice that both start with the same sequence ( e7f1c7d9e4d7d7d6 ) which seems to come from a common beginning X1GRUPPO您会注意到两者都以相同的序列 ( e7f1c7d9e4d7d7d6 ) 开头,这似乎来自一个共同的开头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"根据您提供的输入推断,第一个输入字符串的其余部分以 5 个空格开头,后跟"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.这意味着 C# 代码的完整输入是"X1GRUPPO 00000000167353552" ,这与您提供给 Java 代码的输入不同,然后显然输出不匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM