-
-
Save nazt/540d341c5157e41f368cf6e214ee0d8e to your computer and use it in GitHub Desktop.
Solidity code to convert uint to string (v0.5.x)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function toAsciiString(address x) public view returns (string memory) { | |
bytes memory s = new bytes(40); | |
for (uint i = 0; i < 20; i++) { | |
byte b = byte(uint8(uint(x) / (2**(8*(19 - i))))); | |
byte hi = byte(uint8(b) / 16); | |
byte lo = byte(uint8(b) - 16 * uint8(hi)); | |
s[2*i] = char(hi); | |
s[2*i+1] = char(lo); | |
} | |
return string(s); | |
} | |
function char(byte b) public view returns (byte c) { | |
if (uint8(b) < 10) return byte(uint8(b) + 0x30); | |
else return byte(uint8(b) + 0x57); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function uint2str(uint _i) internal pure returns (string memory _uintAsString) { | |
if (_i == 0) { | |
return "0"; | |
} | |
uint j = _i; | |
uint len; | |
while (j != 0) { | |
len++; | |
j /= 10; | |
} | |
bytes memory bstr = new bytes(len); | |
uint k = len - 1; | |
while (_i != 0) { | |
bstr[k--] = byte(uint8(48 + _i % 10)); | |
_i /= 10; | |
} | |
return string(bstr); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment