[Ethereum] Conversion of address to string in Solidity

errorsoliditytruffle

The Solution given in Convert address to string did not help.

Motive: To convert an address to string type so that I can use it as a parameter to a function for which string type is necessary.

Code Snippet:

function toString(address x) returns (string) {
    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);
}

function getResult() constant returns (string) {
    string memory myAddress = toString(msg.sender);
    return myAddress;
}

Now, when I call getResult() using truffle I get the following error.

Error: Invalid continuation byte
    at Error (native)
    at readContinuationByte (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:59394:9)
    at decodeSymbol (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:59423:12)
    at Object.utf8decode [as decode] (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:59469:33)
    at Object.toUtf8 (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:5184:17)
    at SolidityTypeString.formatOutputString [as _outputFormatter] (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:24766:18)
    at C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:28364:25
    at SolidityTypeString.SolidityType.decode (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:28365:11)
    at C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:59736:29
    at Array.map (native)

Please help understand the root cause of this error as I failed to detect any mistake in my code.

Thank you in advance!

Best Answer

This is right solution:

function addressToString(address _addr) public pure returns(string) {
    bytes32 value = bytes32(uint256(uint160(_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(uint8(value[i + 12] >> 4))];
        str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))];
    }
    return string(str);
}