blockchain - solidity 类型转换: address to string

访问量: 1059

refer to: https://ethereum.stackexchange.com/questions/8346/convert-address-to-string

方法1:

https://ethereum.stackexchange.com/a/126160/30431

OpenZeppelin Strings library

import "@openzeppelin/contracts/utils/Strings.sol";
Strings.toHexString(uint160(address), 20)

方法2:

function toAsciiString(address x) internal pure returns (string memory) {
    bytes memory s = new bytes(40);
    for (uint i = 0; i < 20; i++) {
        bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i)))));
        bytes1 hi = bytes1(uint8(b) / 16);
        bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
        s[2*i] = char(hi);
        s[2*i+1] = char(lo);            
    }
    return string(s);
}

function char(bytes1 b) internal pure returns (bytes1 c) {
    if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
    else return bytes1(uint8(b) + 0x57);
}

订阅/RSS Feed

Subscribe