Solidity Strings – Convert Address to String After Solidity 0.5.x

addressescontract-developmentparsersoliditystring

After solidity 0.5.x release none of conversions from address to string appear to be working. I've tested all of them on remix and got errors like converting bytes to uint or something like this.

This one reverts remix:

function toString(address x) 
    external pure 
    returns (string memory) 
{
    bytes memory b = new bytes(20);
    for (uint i = 0; i < 20; i++)
        b[i] = byte(uint8(uint(x) / (2**(8*(19 - i)))));
    return string(b);
}

This one shows me that something is not allowed from bytes1 to uint256

function addressToString(address _addr) public pure returns(string memory) 
{
    bytes32 value = bytes32(uint256(_addr));
    bytes memory alphabet = "0123456789abcdef";

    bytes memory str = new bytes(51);
    str[0] = '0';
    str[1] = 'x';
    for (uint i = 0; i < 20; i++) {
        str[2+i*2] = alphabet[uint(value[i + 12] >> 4)];
        str[3+i*2] = alphabet[uint(value[i + 12] & 0x0f)];
    }
    return string(str);
}

Is there any proper way to convert address to string? Even if through bytes or bytes32.

The reason why I need this is I have a privileges contract with string => PrivilegeData mapping and Im' calling global privileges from that string like "voting_time_limit". For specific addresses I would like to use calling by address parsed to string like "0x252f…".

Best Answer

Try this out.

pragma solidity > 0.5.1;

contract Test 
{
    
    function test() 
        public 
        view    
        returns (string memory) 
    {
        return addressToString(address(this));
    }

    function addressToString(address _addr) public pure returns(string memory) 
    {
        bytes32 value = bytes32(uint256(uint160(_addr)));
        bytes memory alphabet = "0123456789abcdef";
    
        bytes memory str = new bytes(51);
        str[0] = '0';
        str[1] = 'x';
        for (uint256 i = 0; i < 20; i++) {
            str[2+i*2] = alphabet[uint8(value[i + 12] >> 4)];
            str[3+i*2] = alphabet[uint8(value[i + 12] & 0x0f)];
        }
        return string(str);
    }
}