将十六进制转换为原始字符串值

Convert hex to original string value

在调用以太坊合约方法的 android 应用程序中,我有一个函数 return 在 return (Ethereum Contract ABI) 中给我一个 HEX 值,在这种情况下字符串是 yoooooooo,十六进制是:

 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000009796f6f6f6f6f6f6f6f0000000000000000000000000000000000000000000000

合约 API 向 HEX 添加填充,如 link 中所述。如何在没有填充的情况下从上面的 HEX 值中获取原始值?

请试试这个

String hex = "00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000009796f6f6f6f6f6f6f6f0000000000000000000000000000000000000000000000";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
    String str = hex.substring(i, i+2);
    output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output.toString().trim());

试试这个。

public static String convertHexToStringValue(String hex) {
    StringBuilder stringbuilder = new StringBuilder();
    char[] hexData = hex.toCharArray();
    for (int count = 0; count < hexData.length - 1; count += 2) {
        int firstDigit = Character.digit(hexData[count], 16);
        int lastDigit = Character.digit(hexData[count + 1], 16);
        int decimal = firstDigit * 16 + lastDigit;
        stringbuilder.append((char)decimal);
    }
    return stringbuilder.toString();
}

(我认为)有多种方法可以解决这个问题。我将在这里列出一种解决此类问题的直观方法。

您可以从 String (hex)byte array 再到 String as UTF-8(?)确保您的十六进制字符串没有前导空格和其他东西

public static byte[] hexStringToByteArray(String hex) {
    int l = hex.length();
    byte[] data = new byte[l/2];
    for (int i = 0; i < l; i += 2) {
        data[i/2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                             + Character.digit(hex.charAt(i+1), 16));
    }
    return data;
}

用法:

String b = "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000009796f6f6f6f6f6f6f6f0000000000000000000000000000000000000000000000";
byte[] bytes = hexStringToByteArray(b);
String st = new String(bytes,StandardCharsets.UTF_8);
System.out.println(st);

给出:

? yoooooooo