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.
Asked
Active
Viewed 1,381 times
1
Nick Furfaro
- 167
- 1
- 8
1 Answers
6
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);
}
feamcor
- 86
- 3
new bytes(51);tonew bytes(40);to solve my problem. – Nick Furfaro May 01 '19 at 20:03new bytes(42)(to account for the0x)? – user19510 May 01 '19 at 20:36