65

Solidity 中 uint 转 bytes

 4 years ago
source link: https://www.tuicool.com/articles/Z3iimiV
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

uint 如何转为 bytes类型

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

  1. toBytes0(): 用inline assembly 实现, 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的消耗,大家也可以自己对比。

深入浅出区块链知识星球提供专业的区块链问答服务,如果你需要问题一直没有思路,也许可以考虑咨询下老师。

深入浅出区块链 - 打造高质量区块链技术博客,学区块链都来这里,关注 知乎 、微博。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK