Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

EIPs-CodeLab/EIP-7939

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

3 Commits

Repository files navigation

EIP-7939: Count Leading Zeros (CLZ) Opcode

A Rust implementation demonstrating how the CLZ opcode works in Ethereum.

What is CLZ?

CLZ counts the number of leading zero bits in a 256-bit number. If the input is zero, it returns 256.

Why It Matters

Currently, implementing CLZ in Solidity costs ~184 gas and requires complex bitwise operations. Adding it as a native opcode provides:

  • Lower gas costs for mathematical operations
  • Reduced ZK proving costs
  • Smaller bytecode size

Specification

  • Opcode: 0x1e
  • Gas Cost: 5
  • Stack Input: 1 value (x)
  • Stack Output: 1 value (leading zero count)

Use Cases

  • Mathematical functions (sqrt, log, pow)
  • Calldata compression/decompression
  • Bitmap operations
  • Post-quantum cryptography

Implementation

The core function uses a 4-limb approach for efficiency:

fn clz(x: U256) -> u32 {
 if x.is_zero() {
 return 256;
 }
 
 let limbs = x.0;
 
 if limbs[3] != 0 { return limbs[3].leading_zeros(); }
 if limbs[2] != 0 { return 64 + limbs[2].leading_zeros(); }
 if limbs[1] != 0 { return 128 + limbs[1].leading_zeros(); }
 if limbs[0] != 0 { return 192 + limbs[0].leading_zeros(); }
 
 256
}

Quick Start

# run the demo
cargo run
# run tests
cargo test

Test Results

running 8 tests
test tests::test_clz_zero ... ok
test tests::test_clz_one ... ok
test tests::test_clz_powers_of_two ... ok
test tests::test_clz_various_values ... ok
test tests::test_clz_max_value ... ok
test tests::test_evm_stack_clz ... ok
test tests::test_limb_boundaries ... ok
test tests::test_both_implementations_match ... ok

Examples

CLZ(0) = 256
CLZ(1) = 255
CLZ(256) = 247
CLZ(2^255) = 0
CLZ(2^256 - 1) = 0

Reference

Official EIP: https://eips.ethereum.org/EIPS/eip-7939

License

CC0

About

A Rust implementation of EIP-7939, a new Ethereum opcode that counts the number of leading zero bits in a 256-bit word.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

Contributors

Languages

AltStyle によって変換されたページ (->オリジナル) /