如何在Java中将hexstring转换为ANSI(窗口1252)并将ANSI(window 1252)转换回十六进制字符串?

时间:2019-05-06 07:31:42

标签: java python

如何在Java中将十六进制字符串转换为ansi(窗口1252)和ansi(窗口1252)为十六进制字符串。

python(完美运行)

q = "hex string value"

x = bytes.fromhex(q).decode('ANSI')

a = x.encode("ANSI")
a = a.hex()
if q==a:
    print("Correct")

Java(此代码有问题)

String hexOri = "hex string value";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hexOri.length(); i+=2) {
    String str = hexOri.substring(i, i+2);
    output.append((char)Integer.parseInt(str, 16));
}
System.out.println("ANSI = " + output);
char [] chars = output.toString().toCharArray();
StringBuffer hexOutput = new StringBuffer();

for(int i = 0; i < chars.length; i++){
  hexOutput.append(Integer.toHexString((int)chars[i]));
}
System.out.println("HexOutput = " + hexOutput.toString());
System.out.println(hexOri.equals(hexOutput.toString()));

Python的输出

正确

Python的预期输出

正确

Java输出

错误

Java的预期输出

正确

1 个答案:

答案 0 :(得分:0)

在Java中,字符串是以UTF-16编码的,因此您不能简单地读取/写入字符串的字节来获取所需的编码表示形式。

您应该使用String#getBytes(String str, String charset)将字符串转换为所需的编码,然后序列化为字节数组。

使用new String(buffer,encoding)对字节数组进行解码必须做同样的事情。

在两种情况下,如果使用不带字符集的方法,它将使用JVM实例的默认编码(为系统字符集)。

    public static void main(String[] args) {
        String str = "\tSome text [à]";

        try {
            System.out.println(str); //     Some text [à]

            String windowsLatin1 = "Cp1252";
            String hexString = toHex(windowsLatin1, str);

            System.out.println(hexString); // 09536f6d652074657874205be05d

            String winString = toString(windowsLatin1, hexString);

            System.out.println(winString); //   Some text [à]
        } catch (UnsupportedEncodingException e) {
            // Should not happen.
        }

    }

    public static String toString(String encoding, String hexString) throws UnsupportedEncodingException {
        int length = hexString.length();
        byte [] buffer = new byte[length/2];
        for (int i = 0; i < length ; i+=2) {
            String hexVal = hexString.substring(i,i+2);
            byte code = (byte) Integer.parseInt(hexVal,16);
            buffer[i/2]=code;
        }
        String winString = new String(buffer,encoding);
        return winString;
    }

    public static String toHex(String encoding, String str) throws UnsupportedEncodingException {
        byte[] bytes = str.getBytes(encoding);
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            byte b = bytes[i];
            String hexChar = Integer.toHexString(b & 0xff);
            if(hexChar.length()<2) {
                builder.append('0');
            }
            builder.append(hexChar);
        }
        String hexString = builder.toString(); // 09536f6d652074657874205be05d
        return hexString;
    }