您当前的位置: 首页 >  区块链
  • 0浏览

    0关注

    1477博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

区块链 Solidity中uint转string 数字转字符串

软件工程小施同学 发布时间:2021-12-30 16:32:21 ,浏览量:0

在《Solidity中uint转bytes》中,我们知道unit如何转换成bytes,其实把uint转换成string,就是在最后加上string(bytes变量)即可,如下所示:

复制代码

pragma solidity ^0.4.2;

contract Test {
    
    function toBytesNickJohnson(uint256 x) constant returns (bytes b) {
        b = new bytes(32);
        assembly { mstore(add(b, 32), x) }
    }

    function getStr(uint playChoice) returns (string s) {
        bytes memory c = toBytesNickJohnson(playChoice);
        return string(c);
    }
    
    function toBytesEth(uint256 x) constant returns (bytes b) {
        b = new bytes(32);
        for (uint i = 0; i < 32; i++) {
            b[i] = byte(uint8(x / (2**(8*(31 - i))))); 
        }
    }

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

复制代码

  但是呢,我在这里再附加一种Solidity中uint转string方法,如下所示:

复制代码

pragma solidity ^0.4.2;

contract Test {
    
    function uint2str(uint i) internal returns (string c) {
        if (i == 0) return "0";
        uint j = i;
        uint length;
        while (j != 0){
            length++;
            j /= 10;
        }
        bytes memory bstr = new bytes(length);
        uint k = length - 1;
        while (i != 0){
            bstr[k--] = byte(48 + i % 10);
            i /= 10;
        }
        c = string(bstr);
    }
}

复制代码

Solidity中uint转string - 走看看

关注
打赏
1665320866
查看更多评论
立即登录/注册

微信扫码登录

0.0427s