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 b1;
uint160 b2;
for (uint i = 2; i < 2+2*20; i += 2) {
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;
}
}
``````

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]);
^---------------^
``````
• How did you end up with an address-string in the contract to begin with? i.e., how did that string get into the contract? If you pass it from the off-chain, then you can convert it there beforehand. If it's hard-coded in your contract, then... well, simply get rid of the quotes... I guess I might be missing something in your larger system, but would be happy to know what. – goodvibration Feb 21 at 18:44
• @goodvibration ; It's used in this example: github.com/Azure-Samples/blockchain/blob/master/… – Stef Heyenrath Feb 21 at 19:21

``````function parseAddr(string memory _a) internal pure returns (address _parsedAddress) {
bytes memory tmp = bytes(_a);
uint160 b1;
uint160 b2;
for (uint i = 2; i < 2 + 2 * 20; i += 2) {
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);
}