current position:Home>Convert uint to bytes in solidity

Convert uint to bytes in solidity

2022-02-03 20:46:58 Q & A of Denglian community

Solidity A lot of Hash function ,  Such as :keccak256 Such as need bytes As a parameter , This is sometimes necessary uint Turn into bytes .

uint How to turn into bytes  type




Take the answer 1:

Solidity in uint turn bytes Several ways to ,gas Consumption from less to more :

toBytes0 (): use inline assembly Realization ,Gas The consumption is the least , The most efficient way .

remarks : This implementation will appear in some cases out-of-gas, Unknown cause .

toBytes1 () : use inline assembly Realization recommend ;

toBytes2 () : First convert to bytes32, Then press one by one to copy directly ;toBytes3 () :  Convert directly one by one , Minimum efficiency .

pragma solidity >=0.4.22 <0.7.0;contract uintTobytes {  //  Than  toBytes1  Less  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)))));        }    }}

About gas Consumption of , You can also compare yourself .




copyright notice
author[Q & A of Denglian community],Please bring the original link to reprint, thank you.
https://en.netfreeman.com/2022/02/202202032046558486.html

Random recommended