LoginSignup
0
0

More than 1 year has passed since last update.

uintをbytesに変換する(余計な0を消す)

Last updated at Posted at 2021-10-25

solidity >=0.4.22 <0.9.0;

自分用
Githubに載せるまでもない話(かつハードコードされてるので微妙ですが、一応)

冒頭部分はabi.encodePackedと同等
これだけだと、32byte分、0埋めされているので、0を消したい場合に使う。

uint2bytes.sol
    function uint2bytes(uint value) public returns(bytes memory ){
        bytes memory result = new bytes(32);
        assembly {
           mstore(add(result, 32), value)
        }

        uint len = 0;
        if (value < 256) {
            len = 1;
        }else if (value < 65535) {
            len = 2;
        } else {
            //some code
        }

        return slice(result, 32 - len ,len);
    }

sliceは下記ライブラリつかってますが、普通にresult[32 - len : len]でもいいかも(未確認
https://github.com/GNSPS/solidity-bytes-utils/

参考
https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity/4177

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0