Solidity

是否可以使用 abi.encodeabi.decode 對兩個後續字節數組(大小未知)進行編碼和解碼?

  • July 8, 2021

是否可以使用abi.encodeabi.decode(如下)對兩個後續字節進行編碼和解碼?

bytes memory data = abi.encode(data1, data2);
// later on
(bytes memory data1_recovered, bytes memory data2_recovered) = abi.decode(data, bytes, bytes);

它確實有效。以下範例連接兩個字元串。

function foo(string memory a, string memory b) public view returns (string memory) {
   bytes memory data1 = bytes(a);
   bytes memory data2 = bytes(b);
   bytes memory data = abi.encode(data1, data2);
   return bar(data);
}

function bar(bytes memory data) public view returns (string memory) {
   (bytes memory data1_recovered, bytes memory data2_recovered) = abi.decode(data, (bytes, bytes));
   return string(abi.encodePacked(data2_recovered, " ", data1_recovered));
}

引用自:https://ethereum.stackexchange.com/questions/103136