github.com/0xPolygon/supernets2-node@v0.0.0-20230711153321-2fe574524eaa/test/contracts/uniswap/v2/AddressStringUtil.sol (about)

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  pragma solidity >=0.5.0;
     4  
     5  library AddressStringUtil {
     6      // converts an address to the uppercase hex string, extracting only len bytes (up to 20, multiple of 2)
     7      function toAsciiString(address addr, uint256 len) internal pure returns (string memory) {
     8          require(len % 2 == 0 && len > 0 && len <= 40, 'AddressStringUtil: INVALID_LEN');
     9  
    10          bytes memory s = new bytes(len);
    11          uint256 addrNum = uint256(addr);
    12          for (uint256 i = 0; i < len / 2; i++) {
    13              // shift right and truncate all but the least significant byte to extract the byte at position 19-i
    14              uint8 b = uint8(addrNum >> (8 * (19 - i)));
    15              // first hex character is the most significant 4 bits
    16              uint8 hi = b >> 4;
    17              // second hex character is the least significant 4 bits
    18              uint8 lo = b - (hi << 4);
    19              s[2 * i] = char(hi);
    20              s[2 * i + 1] = char(lo);
    21          }
    22          return string(s);
    23      }
    24  
    25      // hi and lo are only 4 bits and between 0 and 16
    26      // this method converts those values to the unicode/ascii code point for the hex representation
    27      // uses upper case for the characters
    28      function char(uint8 b) private pure returns (bytes1 c) {
    29          if (b < 10) {
    30              return bytes1(b + 0x30);
    31          } else {
    32              return bytes1(b + 0x37);
    33          }
    34      }
    35  }