Strings.sol 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)
  3. pragma solidity ^0.8.0;
  4. /**
  5. * @dev String operations.
  6. */
  7. library Strings {
  8. bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
  9. uint8 private constant _ADDRESS_LENGTH = 20;
  10. /**
  11. * @dev Converts a `uint256` to its ASCII `string` decimal representation.
  12. */
  13. function toString(uint256 value) internal pure returns (string memory) {
  14. // Inspired by OraclizeAPI's implementation - MIT licence
  15. // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
  16. if (value == 0) {
  17. return "0";
  18. }
  19. uint256 temp = value;
  20. uint256 digits;
  21. while (temp != 0) {
  22. digits++;
  23. temp /= 10;
  24. }
  25. bytes memory buffer = new bytes(digits);
  26. while (value != 0) {
  27. digits -= 1;
  28. buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
  29. value /= 10;
  30. }
  31. return string(buffer);
  32. }
  33. /**
  34. * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
  35. */
  36. function toHexString(uint256 value) internal pure returns (string memory) {
  37. if (value == 0) {
  38. return "0x00";
  39. }
  40. uint256 temp = value;
  41. uint256 length = 0;
  42. while (temp != 0) {
  43. length++;
  44. temp >>= 8;
  45. }
  46. return toHexString(value, length);
  47. }
  48. /**
  49. * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
  50. */
  51. function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
  52. bytes memory buffer = new bytes(2 * length + 2);
  53. buffer[0] = "0";
  54. buffer[1] = "x";
  55. for (uint256 i = 2 * length + 1; i > 1; --i) {
  56. buffer[i] = _HEX_SYMBOLS[value & 0xf];
  57. value >>= 4;
  58. }
  59. require(value == 0, "Strings: hex length insufficient");
  60. return string(buffer);
  61. }
  62. /**
  63. * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
  64. */
  65. function toHexString(address addr) internal pure returns (string memory) {
  66. return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
  67. }
  68. }