For some reason beyond my control, I need to store encoded data in a string
variable.
I know abi.encode
and abi.decode
usually work on bytes memory
but I also believe that string memory
can be casted to bytes memory
.
Here is an example contract I use to debug in remix:
pragma solidity ^0.5.0;
contract Test
{
function encode(uint256 a, string calldata b) external pure returns(string memory)
{
return string(abi.encode(a, b));
}
function decode(string calldata a) external pure returns(uint256, string memory)
{
return abi.decode(bytes(a), (uint256, string));
}
}
It works great with some values. For example encode(42, "test")
returns
\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000*\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000@\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0004test\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000
which can then be decoded back to 42, "test"
.
However, for some values, such as 255, "test"
, then I get a revert when trying to decode the encoded string.
Any idea how to solve that ? Is their no other way then to use bytes
instead of string
?