{"eip":3772,"title":"Compressed Integers","description":"Using lossy compression on uint256 to improve gas costs, ideally by a factor up to 4x.","authors":["Soham Zemse (@zemse)"],"status":"Stagnant","type":"Standards Track","category":"ERC","created":"2021-08-27","discussionsTo":"https://github.com/ethereum/EIPs/issues/3772","repo":"ERCs","label":"ERC-3772","officialUrl":"https://eips.ethereum.org/EIPS/eip-3772","sourceUrl":"https://github.com/ethereum/ERCs/blob/master/ERCS/erc-3772.md","url":"https://eips.huatuo.xyz/eip-3772/","tldr":{"en":"A convention for squeezing uint256 money amounts into 64-bit (or other smaller) values using significant bits plus a shift, trading a tiny, controlled precision loss for cheaper storage.","ja":"uint256 の金額を、有効ビットとシフトを使って 64 ビット（またはそれ以下の別のサイズ）の値に押し込むための規約。ごくわずかで制御された精度の損失と引き換えに、ストレージコストを下げる。","ko":"유효 비트와 시프트를 이용해 uint256 금액을 64비트(또는 더 작은 크기)로 압축하는 규약으로, 작고 통제된 정밀도 손실을 감수하는 대신 저장 비용을 줄인다.","zh":"一种约定：用有效位加移位量，把 uint256 的金额压缩成 64 位（或其他更小位宽）的值，以微小且可控的精度损失换取更便宜的存储。"},"tags":["gas","storage","compression","solidity","math"],"explainers":{"en":{"lang":"en","tldr":"A convention for squeezing uint256 money amounts into 64-bit (or other smaller) values using significant bits plus a shift, trading a tiny, controlled precision loss for cheaper storage.","tags":["gas","storage","compression","solidity","math"],"related":[20],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-3772/","markdown":"## What problem does it solve?\n\nToken amounts are almost always stored as `uint256`, which takes a full 32-byte storage slot. Yet the values people actually use span a much smaller range: the author estimates that about 10\u003csup\u003e15\u003c/sup\u003e distinct amounts (roughly 50 bits of information) cover real-world balances for a given token. Most of the 256 bits are wasted, and storage is the most expensive thing a contract does.\n\nERC-3772 proposes a standard lossy compression so several amounts can be packed into one slot, cutting `SSTORE` costs.\n\n## How it works\n\nA compressed integer `cintx` is an `x`-bit value split into two parts:\n\n- **significant**: the top bits of the original number, starting from its first `1` bit.\n- **shift**: how many places to shift `significant` left to rebuild the number.\n\nFor `cint64` up to `cint120`, the lowest 8 bits hold the shift and the rest hold the significant bits (`cint64` = 56 significant bits + 8 shift bits). For `cint128` up to `cint248`, 7 bits are enough for the shift.\n\nThe significant bits are placed in the *high* part on purpose: if a developer forgets to decompress, a small value will not accidentally look correct.\n\nTwo decompression modes are defined, because compression always rounds **down**:\n\n- `decompress`: shift the significant bits back left, filling with zeros (rounds down).\n- `decompressRoundingUp`: same, but fill the dropped low bits with ones (rounds up).\n\nThe recommended rule: when the contract **pays out**, use the rounded-down value; when it **charges** a user, use the rounded-up value. That way rounding never costs the contract money, similar to how careful integer division is handled.\n\nCompressed values are meant for internal storage only. Contracts should expose and do arithmetic on full `uint256` values.\n\n## Sample code\n\nA minimal, self-contained `cint64` codec (illustrative; not audited):\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary CInt64 {\n    function compress(uint256 full) internal pure returns (uint64) {\n        if (full \u003c (1 \u003c\u003c 56)) return uint64(full) \u003c\u003c 8; // fits, shift = 0\n        uint256 bits;                                    // bit length of `full`\n        for (uint256 v = full; v != 0; v \u003e\u003e= 1) bits++;\n        uint256 shift = bits - 56;                        // keep top 56 bits\n        return (uint64(full \u003e\u003e shift) \u003c\u003c 8) | uint64(shift);\n    }\n\n    function decompress(uint64 c) internal pure returns (uint256) {\n        return uint256(c \u003e\u003e 8) \u003c\u003c (c \u0026 0xff);\n    }\n\n    function decompressRoundingUp(uint64 c) internal pure returns (uint256) {\n        uint256 shift = c \u0026 0xff;\n        return (uint256(c \u003e\u003e 8) \u003c\u003c shift) | ((1 \u003c\u003c shift) - 1);\n    }\n}\n\ncontract Vault {\n    using CInt64 for uint256;\n    using CInt64 for uint64;\n\n    struct Position { uint64 amountC; address owner; } // packs into one slot\n    mapping(uint256 =\u003e Position) public positions;\n}\n```\n\n## Things to know\n\n- Status: **Stagnant**. It is a coding convention, not a protocol change, and was never finalised.\n- Compression is lossy: `decompress(compress(x)) \u003c= x`. For `cint64` the error is below 2\u003csup\u003eshift\u003c/sup\u003e, i.e. the 57th significant bit onward is dropped.\n- Gas savings only appear if the compiler can pack the smaller value with other fields into the same slot (field order in structs matters).\n- Do not multiply two compressed values and recompress; precision collapses. Decompress first, then do maths.\n- The spec's own reference snippet has small bugs (e.g. masking the shift with `% (1 \u003c\u003c 9)`); write and test your own codec.\n"},"ja":{"lang":"ja","tldr":"uint256 の金額を、有効ビットとシフトを使って 64 ビット（またはそれ以下の別のサイズ）の値に押し込むための規約。ごくわずかで制御された精度の損失と引き換えに、ストレージコストを下げる。","tags":["gas","storage","compression","solidity","math"],"related":[20],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-3772/","markdown":"## 何を解決するのか\n\nトークンの金額はほとんどの場合 `uint256` で保存され、32 バイトのストレージスロットを丸ごと使います。しかし、実際に使われる値の範囲ははるかに小さいものです。作者は、あるトークンの実世界の残高は、約 10\u003csup\u003e15\u003c/sup\u003e 通りの異なる金額（おおよそ 50 ビットの情報量）でカバーできると見積もっています。256 ビットの大半は無駄になっており、ストレージはコントラクトが行う処理の中で最もコストが高いものです。\n\nERC-3772 は、標準的な非可逆圧縮を提案します。複数の金額を 1 つのスロットに詰め込めるようになり、`SSTORE` のコストを削減できます。\n\n## 仕組み\n\n圧縮された整数 `cintx` は、2 つの部分に分かれた `x` ビットの値です。\n\n- **significant**：元の数値の上位ビットで、最初の `1` ビットから始まります。\n- **shift**：数値を復元するために `significant` を左に何桁シフトするか。\n\n`cint64` から `cint120` までは、下位 8 ビットがシフト量を、残りが有効ビットを保持します（`cint64` = 有効ビット 56 + シフトビット 8）。`cint128` から `cint248` までは、シフト量には 7 ビットで足ります。\n\n有効ビットを意図的に*上位*側に置いているのは、開発者が解凍を忘れても、小さな値がたまたま正しそうに見えることがないようにするためです。\n\n圧縮は常に**切り捨て**になるため、2 つの解凍モードが定義されています。\n\n- `decompress`：有効ビットを左にシフトして戻し、ゼロで埋めます（切り捨て）。\n- `decompressRoundingUp`：同様ですが、失われた下位ビットを 1 で埋めます（切り上げ）。\n\n推奨されるルールは次のとおりです。コントラクトが**支払う**ときは切り捨てた値を使い、ユーザーに**請求する**ときは切り上げた値を使います。こうすれば、丸めによってコントラクトが損をすることはありません。整数除算を慎重に扱う場合と似ています。\n\n圧縮された値は、内部のストレージ専用です。コントラクトは、完全な `uint256` の値を公開し、それに対して演算を行うべきです。\n\n## サンプルコード\n\n最小限で自己完結した `cint64` コーデックです（説明用であり、監査はされていません）。\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary CInt64 {\n    function compress(uint256 full) internal pure returns (uint64) {\n        if (full \u003c (1 \u003c\u003c 56)) return uint64(full) \u003c\u003c 8; // fits, shift = 0\n        uint256 bits;                                    // bit length of `full`\n        for (uint256 v = full; v != 0; v \u003e\u003e= 1) bits++;\n        uint256 shift = bits - 56;                        // keep top 56 bits\n        return (uint64(full \u003e\u003e shift) \u003c\u003c 8) | uint64(shift);\n    }\n\n    function decompress(uint64 c) internal pure returns (uint256) {\n        return uint256(c \u003e\u003e 8) \u003c\u003c (c \u0026 0xff);\n    }\n\n    function decompressRoundingUp(uint64 c) internal pure returns (uint256) {\n        uint256 shift = c \u0026 0xff;\n        return (uint256(c \u003e\u003e 8) \u003c\u003c shift) | ((1 \u003c\u003c shift) - 1);\n    }\n}\n\ncontract Vault {\n    using CInt64 for uint256;\n    using CInt64 for uint64;\n\n    struct Position { uint64 amountC; address owner; } // packs into one slot\n    mapping(uint256 =\u003e Position) public positions;\n}\n```\n\n## 知っておくべきこと\n\n- ステータス：**Stagnant**。これはプロトコルの変更ではなくコーディング規約で、確定されることはありませんでした。\n- 圧縮は非可逆です。`decompress(compress(x)) \u003c= x` となります。`cint64` では、誤差は 2\u003csup\u003eshift\u003c/sup\u003e 未満、つまり 57 番目以降の有効ビットが切り捨てられます。\n- ガスの節約が現れるのは、コンパイラが小さい値を他のフィールドと同じスロットに詰め込める場合だけです（構造体のフィールド順が重要です）。\n- 圧縮された値を 2 つ掛けて再圧縮してはいけません。精度が崩壊します。先に解凍してから計算してください。\n- 仕様自身のリファレンスのスニペットには小さなバグがあります（たとえば、シフトを `% (1 \u003c\u003c 9)` でマスクしている）。自分でコーデックを書き、テストしてください。\n"},"ko":{"lang":"ko","tldr":"유효 비트와 시프트를 이용해 uint256 금액을 64비트(또는 더 작은 크기)로 압축하는 규약으로, 작고 통제된 정밀도 손실을 감수하는 대신 저장 비용을 줄인다.","tags":["gas","storage","compression","solidity","math"],"related":[20],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-3772/","markdown":"## 어떤 문제를 해결하나요?\n\n토큰 금액은 거의 항상 `uint256`으로 저장되어 32바이트 스토리지 슬롯 하나를 통째로 차지합니다. 하지만 실제로 쓰이는 값의 범위는 훨씬 작습니다. 작성자는 특정 토큰의 현실 세계 잔액이 약 10\u003csup\u003e15\u003c/sup\u003e개의 서로 다른 금액(대략 50비트의 정보량)으로 충분히 커버된다고 추정합니다. 256비트 대부분이 낭비되고 있고, 스토리지는 컨트랙트가 하는 일 중 가장 비싼 작업입니다.\n\nERC-3772는 표준 손실 압축을 제안합니다. 여러 금액을 슬롯 하나에 담을 수 있게 되어 `SSTORE` 비용이 줄어듭니다.\n\n## 어떻게 동작하나요?\n\n압축된 정수 `cintx`는 두 부분으로 나뉜 `x`비트 값입니다.\n\n- **significant**: 원래 숫자의 상위 비트로, 첫 번째 `1` 비트부터 시작합니다.\n- **shift**: 숫자를 복원하기 위해 `significant`를 왼쪽으로 몇 칸 시프트하는지.\n\n`cint64`부터 `cint120`까지는 하위 8비트가 시프트 값을, 나머지가 유효 비트를 담습니다(`cint64` = 유효 비트 56 + 시프트 비트 8). `cint128`부터 `cint248`까지는 시프트에 7비트면 충분합니다.\n\n유효 비트를 일부러 *상위* 쪽에 둔 것은, 개발자가 압축 해제를 잊더라도 작은 값이 우연히 맞아 보이지 않게 하기 위해서입니다.\n\n압축은 항상 **내림**이므로 두 가지 압축 해제 모드가 정의되어 있습니다.\n\n- `decompress`: 유효 비트를 왼쪽으로 시프트해 되돌리고 0으로 채웁니다(내림).\n- `decompressRoundingUp`: 같지만 버려진 하위 비트를 1로 채웁니다(올림).\n\n권장 규칙은 이렇습니다. 컨트랙트가 **지급**할 때는 내림한 값을, 사용자에게 **청구**할 때는 올림한 값을 씁니다. 그러면 반올림 때문에 컨트랙트가 손해 볼 일이 없으며, 정수 나눗셈을 조심스럽게 다루는 방식과 비슷합니다.\n\n압축된 값은 내부 저장용으로만 쓰도록 되어 있습니다. 컨트랙트는 전체 `uint256` 값을 노출하고 그 값으로 연산해야 합니다.\n\n## 샘플 코드\n\n최소한의 독립적인 `cint64` 코덱입니다(설명용이며 감사받지 않았습니다).\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary CInt64 {\n    function compress(uint256 full) internal pure returns (uint64) {\n        if (full \u003c (1 \u003c\u003c 56)) return uint64(full) \u003c\u003c 8; // fits, shift = 0\n        uint256 bits;                                    // bit length of `full`\n        for (uint256 v = full; v != 0; v \u003e\u003e= 1) bits++;\n        uint256 shift = bits - 56;                        // keep top 56 bits\n        return (uint64(full \u003e\u003e shift) \u003c\u003c 8) | uint64(shift);\n    }\n\n    function decompress(uint64 c) internal pure returns (uint256) {\n        return uint256(c \u003e\u003e 8) \u003c\u003c (c \u0026 0xff);\n    }\n\n    function decompressRoundingUp(uint64 c) internal pure returns (uint256) {\n        uint256 shift = c \u0026 0xff;\n        return (uint256(c \u003e\u003e 8) \u003c\u003c shift) | ((1 \u003c\u003c shift) - 1);\n    }\n}\n\ncontract Vault {\n    using CInt64 for uint256;\n    using CInt64 for uint64;\n\n    struct Position { uint64 amountC; address owner; } // packs into one slot\n    mapping(uint256 =\u003e Position) public positions;\n}\n```\n\n## 알아둘 점\n\n- 상태: **Stagnant**. 프로토콜 변경이 아니라 코딩 규약이며, 확정된 적이 없습니다.\n- 압축은 손실이 있습니다. `decompress(compress(x)) \u003c= x`입니다. `cint64`에서 오차는 2\u003csup\u003eshift\u003c/sup\u003e 미만, 즉 57번째 유효 비트부터는 버려집니다.\n- 가스 절감은 컴파일러가 더 작은 값을 다른 필드와 같은 슬롯에 패킹할 수 있을 때만 나타납니다(구조체의 필드 순서가 중요합니다).\n- 압축된 값 두 개를 곱한 뒤 다시 압축하지 마세요. 정밀도가 무너집니다. 먼저 압축을 풀고 계산하세요.\n- 명세의 레퍼런스 스니펫에도 작은 버그가 있습니다(예: 시프트를 `% (1 \u003c\u003c 9)`로 마스킹). 직접 코덱을 작성하고 테스트하세요.\n"},"zh":{"lang":"zh","tldr":"一种约定：用有效位加移位量，把 uint256 的金额压缩成 64 位（或其他更小位宽）的值，以微小且可控的精度损失换取更便宜的存储。","tags":["gas","storage","compression","solidity","math"],"related":[20],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-3772/","markdown":"## 它解决什么问题？\n\n代币金额几乎总是以 `uint256` 存储，占用整整一个 32 字节的存储槽。然而人们实际使用的数值范围要小得多：作者估计，对于某个代币，约 10\u003csup\u003e15\u003c/sup\u003e 个不同的金额（大约 50 位的信息量）就足以覆盖现实中的余额。256 位中的大部分都被浪费了，而存储是合约做的所有操作中最昂贵的一项。\n\nERC-3772 提出了一种标准的有损压缩，使多个金额可以打包进同一个存储槽，从而降低 `SSTORE` 成本。\n\n## 它如何运作\n\n压缩整数 `cintx` 是一个 `x` 位的值，分为两部分：\n\n- **significant**：原数字的高位，从其第一个 `1` 位开始。\n- **shift**：把 `significant` 左移多少位才能还原该数字。\n\n对于 `cint64` 到 `cint120`，最低 8 位存放移位量，其余位存放有效位（`cint64` = 56 位有效位 + 8 位移位量）。对于 `cint128` 到 `cint248`，7 位就足够存放移位量。\n\n有效位被有意放在*高位*：如果开发者忘记解压，小数值就不会碰巧看起来是对的。\n\n定义了两种解压模式，因为压缩总是向**下**取整：\n\n- `decompress`：把有效位左移还原，用零填充（向下取整）。\n- `decompressRoundingUp`：同上，但用 1 填充被丢弃的低位（向上取整）。\n\n推荐规则是：合约**付款**时使用向下取整的值；向用户**收费**时使用向上取整的值。这样取整永远不会让合约亏钱，类似于谨慎处理整数除法的方式。\n\n压缩后的值仅用于内部存储。合约应当对外暴露完整的 `uint256` 值，并对其进行运算。\n\n## 示例代码\n\n一个最小的、自包含的 `cint64` 编解码器（仅作说明；未经审计）：\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary CInt64 {\n    function compress(uint256 full) internal pure returns (uint64) {\n        if (full \u003c (1 \u003c\u003c 56)) return uint64(full) \u003c\u003c 8; // fits, shift = 0\n        uint256 bits;                                    // bit length of `full`\n        for (uint256 v = full; v != 0; v \u003e\u003e= 1) bits++;\n        uint256 shift = bits - 56;                        // keep top 56 bits\n        return (uint64(full \u003e\u003e shift) \u003c\u003c 8) | uint64(shift);\n    }\n\n    function decompress(uint64 c) internal pure returns (uint256) {\n        return uint256(c \u003e\u003e 8) \u003c\u003c (c \u0026 0xff);\n    }\n\n    function decompressRoundingUp(uint64 c) internal pure returns (uint256) {\n        uint256 shift = c \u0026 0xff;\n        return (uint256(c \u003e\u003e 8) \u003c\u003c shift) | ((1 \u003c\u003c shift) - 1);\n    }\n}\n\ncontract Vault {\n    using CInt64 for uint256;\n    using CInt64 for uint64;\n\n    struct Position { uint64 amountC; address owner; } // packs into one slot\n    mapping(uint256 =\u003e Position) public positions;\n}\n```\n\n## 需要注意\n\n- 状态：**Stagnant**。这是一种编码约定，而不是协议变更，从未最终定稿。\n- 压缩是有损的：`decompress(compress(x)) \u003c= x`。对于 `cint64`，误差小于 2\u003csup\u003eshift\u003c/sup\u003e，也就是从第 57 个有效位起的内容被丢弃。\n- 只有当编译器能把较小的值与其他字段打包到同一个存储槽时，才会出现 gas 节省（结构体中字段的顺序很重要）。\n- 不要把两个压缩值相乘再重新压缩；精度会崩溃。应先解压，再做运算。\n- 规范自带的参考代码片段有一些小 bug（例如用 `% (1 \u003c\u003c 9)` 对移位量做掩码）；请自行编写并测试你的编解码器。\n"}}}
