Strings.sol 1.9 KB

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