{"eip":7939,"title":"Count leading zeros (CLZ) opcode","description":"Opcode to count the number of leading zero bits in a 256-bit word","authors":["Vectorized (@Vectorized)","Georgios Konstantopoulos (@gakonst)","Jochem Brouwer (@jochem-brouwer)","Ben Adams (@benaadams)","Giulio Rebuffo (@Giulio2002)"],"status":"Final","type":"Standards Track","category":"Core","created":"2025-04-28","discussionsTo":"https://ethereum-magicians.org/t/create-a-new-opcode-for-counting-leading-zeros-clz/10805","repo":"EIPs","label":"EIP-7939","officialUrl":"https://eips.ethereum.org/EIPS/eip-7939","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7939.md","url":"https://eips.huatuo.xyz/eip-7939/","tldr":{"en":"Adds a CLZ opcode (0x1e) that returns the number of leading zero bits in a 256-bit word for 5 gas, replacing a ~184-gas Solidity routine used in math, bitmaps and compression.","ja":"256 ビットのワードの先頭にあるゼロビットの数を 5 ガスで返す CLZ opcode（0x1e）を追加し、数学、ビットマップ、圧縮で使われていた約 184 ガスの Solidity ルーチンを置き換える。","ko":"256비트 워드의 앞쪽 0 비트 개수를 5 가스로 반환하는 CLZ opcode(0x1e)를 추가해, 수학, 비트맵, 압축에서 쓰이던 약 184 가스짜리 Solidity 루틴을 대체한다.","zh":"新增 CLZ opcode（0x1e），以 5 gas 返回 256 位字中前导零的个数，取代数学运算、位图和压缩中使用的约 184 gas 的 Solidity 例程。"},"tags":["evm","opcode","core","math","fusaka"],"explainers":{"en":{"lang":"en","tldr":"Adds a CLZ opcode (0x1e) that returns the number of leading zero bits in a 256-bit word for 5 gas, replacing a ~184-gas Solidity routine used in math, bitmaps and compression.","tags":["evm","opcode","core","math","fusaka"],"related":[7607,145],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-7939/","markdown":"## What problem does it solve?\n\nCounting leading zeros (\"where is the highest set bit?\") is a building block for fixed-point logarithms and powers, square and cube roots, bitmaps that search for the next set bit, byte-string comparison and calldata compression. Many processor architectures, including ARM, have a native instruction for it.\n\nThe EVM did not. The fastest known Solidity version takes about 184 gas, uses large magic constants that bloat bytecode, and relies on several dynamic right shifts, which are expensive inside ZK provers. EIP-7939 adds the operation directly.\n\n## How it works\n\n- New opcode **`CLZ` = `0x1e`**.\n- Pops one value `x`, pushes the number of zero bits before the most significant `1` bit.\n- If `x == 0`, it pushes **256**.\n- Gas cost: **5**, the same as `MUL`.\n\nExamples from the spec's test cases:\n\n| Input | Output |\n| --- | --- |\n| `0x00…00` | 256 |\n| `0x80…00` (top bit set) | 0 |\n| `0x40…00` | 1 |\n| `0x7fff…ff` | 1 |\n| `0x00…01` | 255 |\n\nWhy 256 for zero? It is the next value after 255, so comparisons stay cheap, and `256 \u003e\u003e 3 = 32` gives the number of bytes to skip for an all-zero word. Why CLZ rather than count-trailing-zeros? CTZ can be derived from CLZ by isolating the lowest bit (`x \u0026 -x`), but not the other way round.\n\n## Sample code\n\nReference behaviour in Python, from the spec:\n\n```python\ndef clz(x: int) -\u003e int:\n    assert 0 \u003c= x \u003c 2**256\n    if x == 0:\n        return 256\n    return 256 - x.bit_length()\n\nassert clz(0) == 256\nassert clz(1) == 255\nassert clz(1 \u003c\u003c 255) == 0\n```\n\nRaw bytecode that computes `clz(1)`:\n\n```text\n6001      PUSH1 0x01\n1e        CLZ          ; stack: 0xff (255)\n```\n\nA common use: index of the highest set bit (floor of log2) is `255 - clz(x)` for non-zero `x`.\n\n## Things to know\n\n- **Status: Final.** It is listed in the Fusaka hard fork meta EIP ([EIP-7607](/eip-7607/)), so it only works on chains that have activated that fork; other EVM chains may lag.\n- Contracts that use `CLZ` will revert with an invalid opcode on chains without it. Check the target chain and your compiler's EVM version setting before relying on it.\n- The authors benchmarked it at roughly the cost of `ADD` in compute; the 5 gas price was set to match `MUL` to stay clear of under-pricing.\n- It complements the shift opcodes from [EIP-145](/eip-145/).\n"},"ja":{"lang":"ja","tldr":"256 ビットのワードの先頭にあるゼロビットの数を 5 ガスで返す CLZ opcode（0x1e）を追加し、数学、ビットマップ、圧縮で使われていた約 184 ガスの Solidity ルーチンを置き換える。","tags":["evm","opcode","core","math","fusaka"],"related":[7607,145],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-7939/","markdown":"## 何を解決するのか\n\n先頭のゼロを数えること（「最上位のセットされたビットはどこか」）は、固定小数点の対数やべき乗、平方根や立方根、次にセットされているビットを探すビットマップ、バイト列の比較、calldata 圧縮の基本部品です。ARM を含む多くのプロセッサアーキテクチャには、そのためのネイティブ命令があります。\n\nEVM にはありませんでした。知られている中で最速の Solidity 版は約 184 ガスかかり、バイトコードを肥大させる大きなマジック定数を使い、ZK プルーバー内ではコストが高い動的な右シフトを何度も使います。EIP-7939 はこの演算を直接追加します。\n\n## 仕組み\n\n- 新しい opcode **`CLZ` = `0x1e`**。\n- 値 `x` を 1 つポップし、最上位の `1` ビットより前にあるゼロビットの数をプッシュします。\n- `x == 0` なら **256** をプッシュします。\n- ガスコスト: **5**。`MUL` と同じです。\n\n仕様のテストケースからの例:\n\n| 入力 | 出力 |\n| --- | --- |\n| `0x00…00` | 256 |\n| `0x80…00`（最上位ビットがセット） | 0 |\n| `0x40…00` | 1 |\n| `0x7fff…ff` | 1 |\n| `0x00…01` | 255 |\n\nなぜゼロに対して 256 なのか。255 の次の値だからで、比較が安価に済みます。また `256 \u003e\u003e 3 = 32` により、すべてゼロのワードでスキップすべきバイト数が得られます。なぜ末尾ゼロの数（CTZ）ではなく CLZ なのか。CTZ は、最下位ビットを取り出す（`x \u0026 -x`）ことで CLZ から導けますが、その逆はできないからです。\n\n## サンプルコード\n\n仕様にある Python でのリファレンスの動作:\n\n```python\ndef clz(x: int) -\u003e int:\n    assert 0 \u003c= x \u003c 2**256\n    if x == 0:\n        return 256\n    return 256 - x.bit_length()\n\nassert clz(0) == 256\nassert clz(1) == 255\nassert clz(1 \u003c\u003c 255) == 0\n```\n\n`clz(1)` を計算する生のバイトコード:\n\n```text\n6001      PUSH1 0x01\n1e        CLZ          ; stack: 0xff (255)\n```\n\nよくある使い方: 最上位のセットされたビットのインデックス（log2 の切り捨て）は、非ゼロの `x` に対して `255 - clz(x)` です。\n\n## 知っておくべきこと\n\n- **ステータス: Final。** Fusaka ハードフォークのメタ EIP（[EIP-7607](/eip-7607/)）に挙げられているため、そのフォークを有効化したチェーンでしか動作しません。他の EVM チェーンは遅れる可能性があります。\n- `CLZ` を使うコントラクトは、これを持たないチェーンでは invalid opcode で revert します。頼る前に、対象チェーンとコンパイラの EVM バージョン設定を確認してください。\n- 著者らは、計算コストとしてはおおよそ `ADD` と同程度だとベンチマークしました。5 ガスという価格は、価格の過小設定を避けるため `MUL` に合わせて決められました。\n- [EIP-145](/eip-145/) のシフト opcode を補完するものです。\n"},"ko":{"lang":"ko","tldr":"256비트 워드의 앞쪽 0 비트 개수를 5 가스로 반환하는 CLZ opcode(0x1e)를 추가해, 수학, 비트맵, 압축에서 쓰이던 약 184 가스짜리 Solidity 루틴을 대체한다.","tags":["evm","opcode","core","math","fusaka"],"related":[7607,145],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-7939/","markdown":"## 어떤 문제를 해결하나요?\n\n앞쪽 0의 개수를 세는 것(\"가장 높은 세트된 비트는 어디인가?\")은 고정소수점 로그와 거듭제곱, 제곱근과 세제곱근, 다음 세트된 비트를 찾는 비트맵, 바이트 문자열 비교, calldata 압축의 기본 구성 요소입니다. ARM을 비롯한 많은 프로세서 아키텍처에는 이를 위한 네이티브 명령이 있습니다.\n\nEVM에는 없었습니다. 알려진 가장 빠른 Solidity 버전은 약 184 가스가 들고, 바이트코드를 부풀리는 큰 매직 상수를 쓰며, ZK 증명기 안에서 비용이 큰 동적 오른쪽 시프트를 여러 번 사용합니다. EIP-7939는 이 연산을 직접 추가합니다.\n\n## 어떻게 동작하나요?\n\n- 새 opcode **`CLZ` = `0x1e`**.\n- 값 `x` 하나를 pop하고, 최상위 `1` 비트 앞에 있는 0 비트의 개수를 push합니다.\n- `x == 0`이면 **256**을 push합니다.\n- 가스 비용: **5**, `MUL`과 같습니다.\n\n명세의 테스트 케이스 예시:\n\n| 입력 | 출력 |\n| --- | --- |\n| `0x00…00` | 256 |\n| `0x80…00`(최상위 비트가 세트됨) | 0 |\n| `0x40…00` | 1 |\n| `0x7fff…ff` | 1 |\n| `0x00…01` | 255 |\n\n0에 대해 왜 256일까요? 255 다음 값이라 비교가 저렴하게 유지되고, `256 \u003e\u003e 3 = 32`로 전부 0인 워드에서 건너뛸 바이트 수가 나오기 때문입니다. 왜 뒤쪽 0의 개수(CTZ)가 아니라 CLZ일까요? CTZ는 가장 낮은 비트를 분리(`x \u0026 -x`)해 CLZ로부터 유도할 수 있지만, 반대는 안 되기 때문입니다.\n\n## 샘플 코드\n\n명세의 Python 레퍼런스 동작:\n\n```python\ndef clz(x: int) -\u003e int:\n    assert 0 \u003c= x \u003c 2**256\n    if x == 0:\n        return 256\n    return 256 - x.bit_length()\n\nassert clz(0) == 256\nassert clz(1) == 255\nassert clz(1 \u003c\u003c 255) == 0\n```\n\n`clz(1)`을 계산하는 원시 바이트코드:\n\n```text\n6001      PUSH1 0x01\n1e        CLZ          ; stack: 0xff (255)\n```\n\n흔한 용도: 0이 아닌 `x`에 대해 가장 높은 세트된 비트의 인덱스(log2의 내림)는 `255 - clz(x)`입니다.\n\n## 알아둘 점\n\n- **상태: Final.** Fusaka 하드포크 Meta EIP([EIP-7607](/eip-7607/))에 포함되어 있으므로 해당 포크를 활성화한 체인에서만 동작합니다. 다른 EVM 체인은 뒤처질 수 있습니다.\n- `CLZ`를 쓰는 컨트랙트는 이를 지원하지 않는 체인에서 invalid opcode로 revert됩니다. 의존하기 전에 대상 체인과 컴파일러의 EVM 버전 설정을 확인하세요.\n- 저자들은 연산 비용이 대략 `ADD` 수준이라고 벤치마크했습니다. 5 가스라는 가격은 과소 책정을 피하려고 `MUL`에 맞춰 정했습니다.\n- [EIP-145](/eip-145/)의 시프트 opcode를 보완합니다.\n"},"zh":{"lang":"zh","tldr":"新增 CLZ opcode（0x1e），以 5 gas 返回 256 位字中前导零的个数，取代数学运算、位图和压缩中使用的约 184 gas 的 Solidity 例程。","tags":["evm","opcode","core","math","fusaka"],"related":[7607,145],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-7939/","markdown":"## 它解决什么问题？\n\n统计前导零（\"最高的置位位在哪里？\"）是定点对数和幂运算、平方根和立方根、查找下一个置位位的位图、字节串比较以及 calldata 压缩的基础构件。包括 ARM 在内的许多处理器架构都有对应的原生指令。\n\nEVM 以前没有。已知最快的 Solidity 版本大约需要 184 gas，使用会让字节码膨胀的大型魔数常量，并依赖若干次动态右移，而这在 ZK 证明器中开销很大。EIP-7939 直接加入了这个操作。\n\n## 它如何运作\n\n- 新 opcode **`CLZ` = `0x1e`**。\n- 弹出一个值 `x`，压入最高位 `1` 之前的零位个数。\n- 如果 `x == 0`，则压入 **256**。\n- Gas 成本：**5**，与 `MUL` 相同。\n\n规范测试用例中的示例：\n\n| 输入 | 输出 |\n| --- | --- |\n| `0x00…00` | 256 |\n| `0x80…00`（最高位置位） | 0 |\n| `0x40…00` | 1 |\n| `0x7fff…ff` | 1 |\n| `0x00…01` | 255 |\n\n为什么零对应 256？因为它是 255 之后的下一个值，所以比较的开销仍然很低，而且 `256 \u003e\u003e 3 = 32` 给出了全零字需要跳过的字节数。为什么选 CLZ 而不是统计末尾零的个数（CTZ）？CTZ 可以通过分离最低位（`x \u0026 -x`）由 CLZ 推导出来，反过来则不行。\n\n## 示例代码\n\n规范中给出的 Python 参考行为：\n\n```python\ndef clz(x: int) -\u003e int:\n    assert 0 \u003c= x \u003c 2**256\n    if x == 0:\n        return 256\n    return 256 - x.bit_length()\n\nassert clz(0) == 256\nassert clz(1) == 255\nassert clz(1 \u003c\u003c 255) == 0\n```\n\n计算 `clz(1)` 的原始字节码：\n\n```text\n6001      PUSH1 0x01\n1e        CLZ          ; stack: 0xff (255)\n```\n\n一个常见用法：对于非零的 `x`，最高置位位的索引（log2 的向下取整）是 `255 - clz(x)`。\n\n## 需要注意\n\n- **状态：Final。** 它被列入 Fusaka 硬分叉的 Meta EIP（[EIP-7607](/eip-7607/)），因此只能在已激活该分叉的链上使用；其他 EVM 链可能会滞后。\n- 使用 `CLZ` 的合约在没有该 opcode 的链上会因无效 opcode 而 revert。依赖它之前，请检查目标链以及编译器的 EVM 版本设置。\n- 作者对它做了基准测试，计算开销大致与 `ADD` 相当；5 gas 的定价被设为与 `MUL` 相同，以避免定价过低。\n- 它是对 [EIP-145](/eip-145/) 中移位 opcode 的补充。\n"}},"requiredBy":[7607]}
