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

2024-09-30 02:18:46 发布

您现在位置: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的预期输出

正确


Tags: 字符串outputstringjavaoutsystemintansi
1条回答
网友
1楼 · 发布于 2024-09-30 02:18:46

在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;
    }

相关问题 更多 >

    热门问题