Solidity – Convert Address-String to Ethereum Address in Solidity 0.5.x

addressesstringtype-casting

I'm looking for a Solidity 0.5.x compatible function to convert a string with and address like "0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe" into a real address.

I did use this function:

function stringToAddress(string memory _a) public pure returns (address) {
        bytes memory tmp = bytes(_a);
        uint160 iaddr = 0;
        uint160 b1;
        uint160 b2;
        for (uint i = 2; i < 2+2*20; i += 2) {
            iaddr *= 256;
            b1 = uint160(tmp[i]);
            b2 = uint160(tmp[i+1]);
            if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
            else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
            if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
            else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
            iaddr += (b1*16+b2);
        }
        return address(iaddr);
    }

However this gives me these errors:

VehicleRegistry1.sol:266:18: TypeError: Explicit type conversion not allowed
from "bytes1" to "uint160".
            b1 = uint160(tmp[i]);
                 ^-------------^
VehicleRegistry1.sol:267:18: TypeError: Explicit type conversion not allowed from "bytes1" to "uint160".
            b2 = uint160(tmp[i+1]);
                 ^---------------^

Best Answer

From oraclize contract

function parseAddr(string memory _a) internal pure returns (address _parsedAddress) {
    bytes memory tmp = bytes(_a);
    uint160 iaddr = 0;
    uint160 b1;
    uint160 b2;
    for (uint i = 2; i < 2 + 2 * 20; i += 2) {
        iaddr *= 256;
        b1 = uint160(uint8(tmp[i]));
        b2 = uint160(uint8(tmp[i + 1]));
        if ((b1 >= 97) && (b1 <= 102)) {
            b1 -= 87;
        } else if ((b1 >= 65) && (b1 <= 70)) {
            b1 -= 55;
        } else if ((b1 >= 48) && (b1 <= 57)) {
            b1 -= 48;
        }
        if ((b2 >= 97) && (b2 <= 102)) {
            b2 -= 87;
        } else if ((b2 >= 65) && (b2 <= 70)) {
            b2 -= 55;
        } else if ((b2 >= 48) && (b2 <= 57)) {
            b2 -= 48;
        }
        iaddr += (b1 * 16 + b2);
    }
    return address(iaddr);
}