加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

Solidity中uint转string

发布时间:2020-12-14 02:41:29 所属栏目:Windows 来源:网络整理
导读:在《Solidity中uint转bytes》中,我们知道unit如何转换成bytes,其实把uint转换成string,就是在最后加上string(bytes变量)即可,如下所示: pragma solidity ^0.4.2; contract Test { function toBytesNickJohnson(uint256 x) constant returns (bytes b) {

  在《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) public 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);
}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读