Skip to content

Latest commit

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date

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:

fnclz(x:U256) -> u32{if x.is_zero(){return256;}let limbs = x.0;if limbs[3] != 0{return limbs[3].leading_zeros();}if limbs[2] != 0{return64 + limbs[2].leading_zeros();}if limbs[1] != 0{return128 + limbs[1].leading_zeros();}if limbs[0] != 0{return192 + 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) = 256CLZ(1) = 255CLZ(256) = 247CLZ(2^255) = 0CLZ(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

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages