0

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]);
                 ^---------------^
2
  • 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. Commented Feb 21, 2019 at 18:44
  • @goodvibration ; It's used in this example: github.com/Azure-Samples/blockchain/blob/master/… Commented Feb 21, 2019 at 19:21

1 Answer 1

2

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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.