I've seen another question answered with a solution to this here : Convert address to string but it results in an error so I'm re-asking. The error is:
"TypeError: Operator < not compatible with types bytes1 and int_const 10"
For context, I'm trying to build a function to dynamically construct a URI which includes the address of the contract where the function lives.
Solution taken from previous posts but fixed in order to avoid casting errors presented on latest Solidity versions...
function addressToString(address _address) public pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_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);
}
-
This seems to return the address as a string, but with trailing 'null' characters. For example, if the address 0xaaadeed4c0b861cb36f4ce006a9c90ba2e43fdc2 is passed to the function, the return value (in a js test) is : '0xaaadeed4c0b861cb36f4ce006a9c90ba2e43fdc2\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000' I wonder if I can tweak it to trim those off... – Nick Furfaro May 1 '19 at 19:52
-
EDIT: I changed
new bytes(51);
tonew bytes(40);
to solve my problem. – Nick Furfaro May 1 '19 at 20:03 -
1
-