2

I am trying to find the correct way to concatenate an Ethereum address to a string in Solidity v0.6.7

I tried the following but it did not seem to work :

    function append(string a, address b) internal pure returns (string) {

    return string(abi.encodePacked(a, b));

}

Any point in the correct direction would be appreciated

1
  • You'll probably have to write a function that converts address to string using a for loop.
    – hrkrshnn
    May 23 '21 at 17:02
-1

I figured it out. This is the working function :

function addressToString(address _address) internal pure returns(string memory) {
   bytes32 _bytes = bytes32(uint256(uint160(_address)));
   bytes memory HEX = "0123456789abcdef";
   bytes memory _string = new bytes(42);
   _string[0] = '0';
   _string[1] = 'x';
   for(uint i = 0; i < 20; i++) {
       _string[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
       _string[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
   }
   return string(_string);
}
1
  • This is to cast an address to a string, not to concatenate (and I know you’re answering yourself) Nov 7 '21 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy