//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; library LibUintToString { uint256 private constant MAX_UINT256_STRING_LENGTH = 78; uint8 private constant ASCII_DIGIT_OFFSET = 48; /// @dev Converts a `uint256` value to a string. /// @param n The integer to convert. /// @return nstr `n` as a decimal string. function toString(uint256 n) internal pure returns (string memory nstr) { if (n == 0) { return '0'; } // Overallocate memory nstr = new string(MAX_UINT256_STRING_LENGTH); uint256 k = MAX_UINT256_STRING_LENGTH; // Populate string from right to left (lsb to msb). while (n != 0) { assembly { let char := add(ASCII_DIGIT_OFFSET, mod(n, 10)) mstore(add(nstr, k), char) k := sub(k, 1) n := div(n, 10) } } assembly { // Shift pointer over to actual start of string. nstr := add(nstr, k) // Store actual string length. mstore(nstr, sub(MAX_UINT256_STRING_LENGTH, k)) } return nstr; } }