gpt4 book ai didi

java - 十六进制到 ASCII 显示不同的结果以纠正 PHP 实现

转载 作者:行者123 更新时间:2023-12-02 09:02:53 25 4
gpt4 key购买 nike

我需要一种将十六进制转换为 ascii 的方法,大多数似乎是以下方法的变体:

public String hexToAscii(String hex) {
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
for(int i = 0; i < hex.length() - 1; i += 2){
String output = hex.substring(i, (i + 2));
int decimal = Integer.parseInt(output, 16);
sb.append((char)decimal);
temp.append(decimal);
}
return sb.toString();
}

这个想法是看

hexToAscii("51d37bdd871c9e1f4d5541be67a6ab625e32028744d7d4609d0c37747b40cd2d");

如果我打印结果,我会得到

-Í@{t7?`Ô×D?2^b«¦g¾AUM??Ý{ÓQ.  

但这不是我需要的结果。一位 friend 在 PHP 中得到了正确的结果,即以下字符串的反转:

QÓ{݇žMUA¾g¦«b^2‡D×Ô`7t{@Í-

很明显,他的 hexToAscii 函数正在编码某些字符,而我的则不是。不太确定为什么会出现这种情况,但是我如何在 Java 中实现这个版本?

最佳答案

假设您的输入字符串在in中,我会使用这样的方法

public static byte[] decode(String in) {
if (in != null) {
in = in.trim();
List<Byte> bytes = new ArrayList<Byte>();
char[] chArr = in.toCharArray();

int t = 0;
while (t + 1 < chArr.length) {
String token = "" + chArr[t] + chArr[t + 1];
// This subtracts 128 from the byte value.
int b = Byte.MIN_VALUE
+ Integer.valueOf(token, 16);
bytes.add((byte) b);
t += 2;
}
byte[] out = new byte[bytes.size()];
for (int i = 0; i < bytes.size(); ++i) {
out[i] = bytes.get(i);
}
return out;
}
return new byte[] {};
}

然后你可以像这样使用它

new String(decode("51d37bdd871c9e1f4d5541be67a6ab625e"
+"32028744d7d4609d0c37747b40cd2d"))

关于java - 十六进制到 ASCII 显示不同的结果以纠正 PHP 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20309451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com