Skip to content

Instantly share code, notes, and snippets.

@CJ42
Created April 14, 2022 19:43
Show Gist options
  • Save CJ42/7297ff23f1fd76a376705c71d68c378d to your computer and use it in GitHub Desktop.
Save CJ42/7297ff23f1fd76a376705c71d68c378d to your computer and use it in GitHub Desktop.
function `toString` as an example of how `while` loops are used in Solidity
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
/// @title HexStrings
/// Based on https://github.com/OpenZeppelin/openzeppelin-contracts/blob/8dd744fc1843d285c38e54e9d439dea7f6b93495/contracts/utils/Strings.sol
library HexStrings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/// @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/// @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
// function body (omitted for brievity)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment