1

编辑:用下面的代码解决了这个问题:

    String tokenId="0x1800000000001289000000000000000000000000000000000000000000000000";

    BigInteger token1;
    if (tokenId.startsWith("0x")){
        token1=new BigInteger(tokenId.substring(2),16);

我有一个长字符串,我需要将其分配为 BigInteger 并将其传递给 Web3j 库的另一个方法。但是,我一直收到数字格式异常。对此有什么帮助吗?

下面是抛出异常的方法:

public void getBalance1155(String walletAddress) throws ExecutionException, InterruptedException {

    //define constant values

    Web3j web3j=Web3j.build(new HttpService("https://mainnet.infura.io/v3/<apiKey>>"));
    String contractAddress = "0xfaaFDc07907ff5120a76b34b731b278c38d6043C";
    BigInteger tokenId=new BigInteger("0x1800000000001289000000000000000000000000000000000000000000000000",16);
    NoOpProcessor processor = new NoOpProcessor(web3j);
    Credentials credentials = Credentials.create("privatekey");
    TransactionManager txManager = new FastRawTransactionManager(web3j, credentials, processor);

    //Query Blockchain to get balance of WALLETADDRESS from Contract for given TokenID

    ERC1155 token = ERC1155.load(contractAddress, web3j, txManager, DefaultGasProvider.GAS_PRICE, DefaultGasProvider.GAS_LIMIT);
    RemoteCall<BigInteger> sendCall = token.balanceOf(walletAddress, tokenId);
    BigInteger balance=sendCall.sendAsync().get();
    log.info("balance >>>>>> " +balance);
}

这是例外:

java.lang.NumberFormatException:对于输入字符串:“0x1800000000001289000000000000000000000000000000000000”在 java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 在 java.base/java.lang.Long.parseLong(Long.java: ) 在 java.base/java.lang.Long.parseLong(Long.java:817)

4

3 回答 3

1

0x从字符串中删除无关的。

BigInteger的构造函数的文档说

String 表示由一个可选的减号或加号组成,后跟指定基数的一个或多个数字序列。

[...]字符串不能包含任何无关的字符

没有提到像0x(或0八进制)这样的前缀。

于 2020-02-28T09:49:54.397 回答
1

您需要删除0x,您可以通过toString(16)在 BigInteger 上使用来检索六进制值

BigInteger tokenId=new BigInteger("1800000000001289000000000000000000000000000000000000000000000000",16);
System.out.println("tokenId.toString(16) = " + tokenId.toString(16));
System.out.println("tokenId.toString(10) = " + tokenId.toString(10));

String originalString = "0x" + tokenId.toString(16);
System.out.println("originalString = " + originalString);

输出:

tokenId.toString(16) = 1800000000001289000000000000000000000000000000000000000000000000
tokenId.toString(10) = 10855508365998423105807514254364715762064874182780947284375732482585619595264
originalString = 0x1800000000001289000000000000000000000000000000000000000000000000
于 2020-02-28T09:51:48.017 回答
0

由于您已经在使用 web3j,您可以使用Numeric.decodeQuantity("0x1800000000001289000000000000000000000000000000000000000000000000")此将十六进制解码为BigInteger

于 2020-03-06T16:20:30.603 回答