Solidity中uint转string
  在《》中,我们知道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}
}
  但是呢,我在这⾥再附加⼀种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);
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。