From f82ef072b748e6559648b9c89d55803530e37a05 Mon Sep 17 00:00:00 2001 From: andrekorol Date: Fri, 18 Dec 2020 05:12:51 -0300 Subject: [PATCH] Fix conversion from uint256 to string --- contracts/utils/Strings.sol | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/contracts/utils/Strings.sol b/contracts/utils/Strings.sol index 52b7ec63502..0e67dc7c4d2 100644 --- a/contracts/utils/Strings.sol +++ b/contracts/utils/Strings.sol @@ -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); } }