Strings.sol 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts v4.4.1 (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. /**
  10. * @dev Converts a `uint256` to its ASCII `string` decimal representation.
  11. */
  12. function toString(uint256 value) internal pure returns (string memory) {
  13. // Inspired by OraclizeAPI's implementation - MIT licence
  14. // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
  15. if (value == 0) {
  16. return "0";
  17. }
  18. uint256 temp = value;
  19. uint256 digits;
  20. while (temp != 0) {
  21. digits++;
  22. temp /= 10;
  23. }
  24. bytes memory buffer = new bytes(digits);
  25. while (value != 0) {
  26. digits -= 1;
  27. buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
  28. value /= 10;
  29. }
  30. return string(buffer);
  31. }
  32. /**
  33. * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
  34. */
  35. function toHexString(uint256 value) internal pure returns (string memory) {
  36. if (value == 0) {
  37. return "0x00";
  38. }
  39. uint256 temp = value;
  40. uint256 length = 0;
  41. while (temp != 0) {
  42. length++;
  43. temp >>= 8;
  44. }
  45. return toHexString(value, length);
  46. }
  47. /**
  48. * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
  49. */
  50. function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
  51. bytes memory buffer = new bytes(2 * length + 2);
  52. buffer[0] = "0";
  53. buffer[1] = "x";
  54. for (uint256 i = 2 * length + 1; i > 1; --i) {
  55. buffer[i] = _HEX_SYMBOLS[value & 0xf];
  56. value >>= 4;
  57. }
  58. require(value == 0, "Strings: hex length insufficient");
  59. return string(buffer);
  60. }
  61. }