solidity – How to Convert Bytes to Address in Solidity

solidity

How to convert bytes or string (eg: 0xf2bd5de8b57ebfc45dcee97524a7a08fccc80aef) to address in solidity?

Best Answer

I feel like there might be a more efficient way to do this but here's my naive solution:

function bytesToAddress (bytes b) constant returns (address) {
    uint result = 0;
    for (uint i = 0; i < b.length; i++) {
        uint c = uint(b[i]);
        if (c >= 48 && c <= 57) {
            result = result * 16 + (c - 48);
        }
        if(c >= 65 && c<= 90) {
            result = result * 16 + (c - 55);
        }
        if(c >= 97 && c<= 122) {
            result = result * 16 + (c - 87);
        }
    }
    return address(result);
}