将hex转换为原始字符串值

时间:2016-04-05 03:52:49

标签: java android ethereum

在一个调用以太坊契约方法的Android应用程序中,我有一个函数,它返回一个HEX值作为回报(Ethereum Contract ABI),在这种情况下,字符串是yoooooooo,HEX是:

 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000009796f6f6f6f6f6f6f6f0000000000000000000000000000000000000000000000

enter image description here

合同API按照链接中的说明向HEX添加填充。如何在没有填充的情况下从上面的HEX值中获取原始值?

3 个答案:

答案 0 :(得分:2)

请尝试这个

tf.placeholder(dtype, shape=None, name=None)

答案 1 :(得分:2)

尝试这个。

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();
}

答案 2 :(得分:-1)

(我认为)有可能有多种方法来解决这个问题。我将在此列出一种直观的方式来解决这样的问题。

您可以从String (hex)转到byte arrayString 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