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

Posted 软件工程小施同学

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了区块链 Solidity中uint转string 数字转字符串相关的知识,希望对你有一定的参考价值。

在《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 - 走看看

以上是关于区块链 Solidity中uint转string 数字转字符串的主要内容,如果未能解决你的问题,请参考以下文章

区块链 solidity 快排

java玩转区块链-基础篇-solidity语法-基础类型

《solidity学习笔记》chapter 2-solidity基础知识

Solidity基础变量总结

区块链开发之Solidity编程基础合约语句及函数修饰符

区块链开发之Solidity编程基础