Solidity 中 uint 转为 bytes

  • Tiny熊
  • 更新于 2023-05-24 15:54
  • 阅读 13488

Solidity 中很多Hash函数, 如:keccak256  等需要bytes作为一个参数,这个时候有时需要把uint转化为bytes 。

Solidity 中很多Hash函数, 如:keccak256  等需要bytes作为一个参数,这个时候有时需要把uint转化为bytes 。

uint 如何转为 bytes 类型

Solidity 中 uint 转 bytes 的几种方法,gas 消耗从少到多:

  1. toBytes0(): 用inline assembly 实现, Gas 消耗最少,最高效的方法。

    备注: 这个实现在某情况下会出现out-of-gas, 原因未知。

  2. toBytes1() : 用inline assembly 实现 推荐

  3. toBytes2() : 先转化为bytes32,再按一个个直接复制;

  4. toBytes3() : 按一个个直接转换,效率最低。


pragma solidity >=0.4.22 <0.7.0;

contract uintTobytes {

  // 比 toBytes1 少 15% de gas
    function toBytes0(uint _num) public returns (bytes memory _ret) {
      assembly {
        _ret := mload(0x10)
        mstore(_ret, 0x20)
        mstore(add(_ret, 0x20), _num)
        }
    }

    function toBytes1(uint256 x) public  returns (bytes memory b) {
        b = new bytes(32);
        assembly { mstore(add(b, 32), x) }
    }

    function toBytes2(uint256 x) public  returns (bytes memory c) {
        bytes32 b = bytes32(x);
        c = new bytes(32);
        for (uint i=0; i < 32; i++) {
            c[i] = b[i];
        }
    }

    function toBytes3(uint256 x) public  returns (bytes memory b) {
        b = new bytes(32);
        for (uint i = 0; i < 32; i++) {
            b[i] = byte(uint8(x / (2**(8*(31 - i)))));
        }
    }

}

关于gas的消耗,大家也可以自己对比。

原问答链接: https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity

学习中如遇问题,欢迎到区块链技术问答提问,这里有老师为你解惑。

点赞 0
收藏 1
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
Tiny熊
Tiny熊
0xD682...E8AB
登链社区发起人 通过区块链技术让世界变得更好而尽一份力。