Skip to content

Commit

Permalink
Fix conversion from uint256 to string
Browse files Browse the repository at this point in the history
  • Loading branch information
andrekorol committed Dec 18, 2020
1 parent f9173c7 commit f82ef07
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions contracts/utils/Strings.sol
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,29 @@ library Strings {
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

if (value == 0) {
return "0";
}

uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
bytes memory reversed = new bytes(digits + 1);
uint256 i = 0;
while (value != 0) {
uint256 remainder = value % 10;
value /= 10;
reversed[i++] = bytes1(uint8(48 + remainder));
}

bytes memory buffer = new bytes(i);
for (uint256 j = 1; j <= i ; j++) {
buffer[j - 1] = reversed[i - j];
}

return string(buffer);
}
}

0 comments on commit f82ef07

Please sign in to comment.