gpt4 book ai didi

solidity - 如何在 solidity 中将字节转换为 uint256

转载 作者:行者123 更新时间:2023-12-02 18:10:23 45 4
gpt4 key购买 nike

我正在尝试将字节可靠地转换为 uint256。这是坚固的代码,

// 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' +

帮我解决这个问题。

最佳答案

在 solidy 0.8.5 中你可以做到

bytes b = ...;
uint256 num = uint256(bytes32(b));

关于solidity - 如何在 solidity 中将字节转换为 uint256,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72465041/

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