Solidity 中 uint 转为 bytes

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

uint 如何转为 bytes 类型

请先 登录 后评论

最佳答案 2019-12-10 15:51

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

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

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

toBytes1 () : 用 inline assembly 实现 推荐

toBytes2 () : 先转化为 bytes32,再按一个个直接复制; 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 的消耗,大家也可以自己对比。

请先 登录 后评论

其它 0 个回答