Created
May 2, 2022 21:18
-
-
Save transmissions11/c1b9c6042fe75843fddafe7472cd1544 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//SPDX-License-Identifier: Unlicense | |
pragma solidity >=0.8.0; | |
library LibString { | |
function toString(uint256 n) internal pure returns (string memory str) { | |
if (n == 0) return "0"; // Otherwise it'd output an empty string for 0. | |
assembly { | |
let k := 78 // Start with the max length a uint256 string could be. | |
// We'll store our string at the first chunk of free memory. | |
str := mload(0x40) | |
// The length of our string will start off at the max of 78. | |
mstore(str, k) | |
// Update the free memory pointer to prevent overriding our string. | |
// Add 128 to the str pointer instead of 78 because we want to maintain | |
// the Solidity convention of keeping the free memory pointer word aligned. | |
mstore(0x40, add(str, 128)) | |
// We'll populate string from right to left. | |
// prettier-ignore | |
for {} n {} { | |
// The ASCII digit offset for '0' is 48. | |
let char := add(48, mod(n, 10)) | |
// Write the current character into str. | |
mstore(add(str, k), char) | |
k := sub(k, 1) | |
n := div(n, 10) | |
} | |
// Shift the pointer to the start of the string. | |
str := add(str, k) | |
// Set the length of the string to the correct value. | |
mstore(str, sub(78, k)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment