> For the complete documentation index, see [llms.txt](https://chihaolu.gitbook.io/all-in-one-solidity/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://chihaolu.gitbook.io/all-in-one-solidity/part-i-basic/chapter-7-jue-se-he-quan-ju-xun-xi-global-variables/abi.md).

# 【ABI】

encode（編碼）、decode（解碼）

* `abi.decode(bytes memory encodedData, (...)) returns (...)`: 對特定資料進行 ABI-解碼
* `abi.encode(...) returns (bytes memory)`: 對特定參數進行 ABI 編碼
* `abi.encodePacked(...) returns (bytes memory)`: 對給定參數執行非特定的包裝模式編碼（Non-standard Packed Mode）
* `abi.encodeWithSelector(bytes4 selector, ...) returns (bytes memory)`: 對特定參數從第二個或前置特定的 4bytes selector 來做 ABI-encodes
  * 換句話說，對給定參數進行編碼，並以給定的函數選擇器作為起始的4 字節數據一起返回
* `abi.encodeWithSignature(string memory signature, ...) returns (bytes memory)`: 效用等同於 `abi.encodeWithSelector(bytes4(keccak256(bytes(signature))), ...)`

`abi.encodePacked` 為非特定的包裝模式（Non-standard Packed Mode）

* 長度低於32 bytes 的類型不會進行符號擴展也不會補零
* 動態類型會直接進行編碼，並不會包含長度訊息

```solidity
(uint a, uint[2] memory b, bytes memory c) = abi.decode(data, (uint, uint[2], bytes))
```

對以下訊息進行編碼 `int16(-1), bytes1(0x42), uint16(0x03), string("Hello, world!")` results in:

```solidity
0xffff42000348656c6c6f2c20776f726c6421
  ^^^^                                 int16(-1)
      ^^                               bytes1(0x42)
        ^^^^                           uint16(0x03)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^ string("Hello, world!") without a length field
```
