如何在Solidity中将字节转换为uint256

3
我将尝试在Solidity中将字节转换为uint256。以下是Solidity代码:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;

contract Sample {

    function getValue(bytes memory a) external pure returns(uint256 value) {
        assembly {
            value := mload(add(a, 0x20))
        }
    }
}

然后我部署了那段代码ganache-cli,在truffle控制台中我尝试调用以下代码:getValue

(await contract.getValue(web3.utils.hexToBytes('0xa'))).toString()

我原本期望返回值为10。但是我却得到了以下错误提示:
Thrown:
TypeError: param.substring is not a function
    at evalmachine.<anonymous>:1:19
    at evalmachine.<anonymous>:2:49
    at sigintHandlersWrap (vm.js:269:15)
    at Script.runInContext (vm.js:124:14)
    at runScript (/Users/xyz/.nvm/versions/node/v12.14.0/lib/node_modules/truffle/build/webpack:/packages/core/lib/console.js:366:1)
    at Console.interpret (/Users/xyz/.nvm/versions/node/v12.14.0/lib/node_modules/truffle/build/webpack:/packages/core/lib/console.js:381:1)
    at bound (domain.js:419:14)
    at REPLServer.runBound [as eval] (domain.js:432:12)
    at REPLServer.onLine (repl.js:715:10)
    at REPLServer.emit (events.js:210:5)
    at REPLServer.EventEmitter.emit (domain.js:475:20)
    at REPLServer.Interface._onLine (readline.js:316:10)
    at REPLServer.Interface._line (readline.js:693:8)
    at REPLServer.Interface._ttyWrite (readline.js:1019:14) {
  hijackedStack: 'TypeError: param.substring is not a function\n' +

帮我解决这个问题。

2个回答

6
在Solidity 0.8.5中,您可以进行以下操作。
bytes b = ...;
uint256 num = uint256(bytes32(b));

小心!只有在确定你拥有的字节数据<=32字节时,才使用这个语法。否则,将其转换为bytes32将截断数据到32字节,你将无法恢复正确的整数。一般来说,对于大多数使用情况来说,这应该是可以的,因为2 ^ 32是使用bytes32可以表示的整数大小。如果由字节表示的整数大于值2 ^ 32,则在转换为bytes32时应该要担心。 - undefined

1

由于bytes是一个动态大小的字节数组,因此您无法将bytes转换为uint256。

如果您确实需要进行此转换,请改用bytes32(或任何其他固定大小的字节数组),然后通过简单的强制转换将其转换为uint256:

function two(bytes32 inBytes) pure public returns (uint256 outUint) {
      return uint256(inBytes);
}

得到相同的错误。我认为我没有正确地从truffle控制台调用。在将sliceUint方法设置为external后,我像这样调用await contract.sliceUint(web3.utils.hexToBytes('0xa'), 0) - sel
我已经更新了适用于我的答案。如果对你有用,请告诉我。 - Sagar Barapatre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接