Skip to main content
This page is a placeholder. All examples on this page are currently AI-generated and are not correct. This documentation will be completed in the future with accurate, tested examples.

Overview

Arithmetic operations provide integer math on 256-bit (32-byte) unsigned values. All operations use modular arithmetic (mod 2^256) with wrapping overflow/underflow semantics, matching the behavior of hardware integer registers. 11 opcodes enable:
  • Basic arithmetic: ADD, MUL, SUB, DIV, MOD
  • Signed operations: SDIV, SMOD
  • Modular arithmetic: ADDMOD, MULMOD
  • Exponentiation: EXP
  • Type extension: SIGNEXTEND

Opcodes

Overflow Semantics

Wrapping Operations

ADD, MUL, SUB use wrapping arithmetic:
No exceptions thrown - values wrap around modulo 2^256.

Division by Zero

DIV and MOD return 0 when dividing by zero (not an exception):
This prevents DOS attacks via division by zero exceptions.

Signed Arithmetic

Two’s Complement Representation

SDIV and SMOD interpret 256-bit values as signed integers:
  • Range: -2^255 to 2^255 - 1
  • Negative flag: Bit 255 (most significant bit)
  • Encoding: Two’s complement

Edge Case: MIN_INT / -1

Special handling for minimum signed integer divided by -1:

Modular Arithmetic

ADDMOD and MULMOD

Perform operations in arbitrary precision before taking modulo:
Critical for cryptographic operations where intermediate overflow would produce incorrect results.

Modulo by Zero

Returns 0 when N = 0 (matches DIV/MOD behavior).

Exponentiation

Dynamic Gas Cost

EXP charges 10 gas base + 50 gas per byte of exponent:
Small exponents (0-255): 10-60 gas Large exponents (2^256-1): 10 + 50*32 = 1610 gas

Algorithm

Uses square-and-multiply for efficiency, but still constrained by gas limits.

Sign Extension

SIGNEXTEND Operation

Extends the sign bit from a specified byte position:
Used to convert smaller signed integers (int8, int16, etc.) to 256-bit signed representation.

Gas Costs

Common Patterns

Safe Math (Pre-Solidity 0.8.0)

Before built-in overflow checking:
Solidity 0.8.0+ has built-in overflow checks (adds REVERT on overflow).

Efficient Modular Exponentiation

For large modular exponentiation, use MODEXP precompile (0x05) instead of combining EXP + MOD:

Division with Rounding

EVM division truncates toward zero:

Implementation

TypeScript

Zig

Edge Cases

Maximum Values

Zero Inputs

Security Considerations

Overflow Attacks

Pre-Solidity 0.8.0, unchecked arithmetic enabled overflow attacks:
Modern Solidity includes automatic overflow checks (costs ~20 extra gas per operation).

Division by Zero

Always returns 0 (not exception), can cause logic errors:

Modular Arithmetic Precision

Use ADDMOD/MULMOD for cryptographic operations to avoid intermediate overflow:

Benchmarks

Relative performance (gas costs reflect computational complexity): See BENCHMARKING.md for detailed benchmarks.

References