在《Solidity中uint轉bytes》中,咱們知道unit如何轉換成bytes,其實把uint轉換成string,就是在最後加上string(bytes變量)便可,以下所示:html
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方法,以下所示:ui
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); } }