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

Opcode: 0x18 Introduced: Frontier (EVM genesis) XOR performs bitwise exclusive OR on two 256-bit unsigned integers. Each bit in the result is 1 if the corresponding bits in the operands differ (one is 1, the other is 0). This operation is fundamental for toggling bits, comparing equality, and cryptographic operations. Primary uses: toggling flags, comparing values for differences, symmetric encryption, checksum calculations.

Specification

Stack Input:
Stack Output:
Gas Cost: 3 (GasFastestStep) Truth Table (per bit):

Behavior

XOR pops two values from the stack, performs bitwise XOR on each corresponding bit pair, and pushes the result. The operation is:
  • Commutative: a ^ b = b ^ a
  • Associative: (a ^ b) ^ c = a ^ (b ^ c)
  • Identity element: a ^ 0 = a
  • Self-inverse: a ^ a = 0
  • Involution: (a ^ b) ^ b = a

Examples

Toggle Bit

Compare for Differences

Simple Encryption (XOR Cipher)

Swap Variables (XOR Swap)

XOR as NOT (with all ones)

Gas Cost

Cost: 3 gas (GasFastestStep) XOR shares the lowest gas tier with:
  • AND (0x16), OR (0x17), NOT (0x19)
  • BYTE (0x1a)
  • SHL (0x1b), SHR (0x1c), SAR (0x1d)
  • ADD (0x01), SUB (0x03)
  • Comparison operations

Edge Cases

Identity Element

Self-Inverse

Involution Property

XOR as NOT

Complementary Patterns

Stack Underflow

Out of Gas

Common Usage

Toggle Feature Flags

Fast Equality Check

Checksum Calculation

Symmetric Cipher (One-Time Pad)

In-Place Swap (Gas-Efficient)

Masking with Inversion

Implementation

Testing

Test Coverage

Edge Cases Tested

  • Basic XOR operations (truth table)
  • Identity element (XOR with 0)
  • Self-inverse property (a ^ a = 0)
  • Involution property ((a ^ b) ^ b = a)
  • XOR as NOT (with MAX_UINT256)
  • Bit toggling
  • Equality detection
  • Commutative property
  • Stack underflow
  • Out of gas

Security

Weak Encryption

Mitigation: Use unique keys (one-time pad) or proper encryption (AES):

XOR Swap Pitfalls

Incorrect Equality Check

Checksum Vulnerabilities

Benchmarks

XOR is one of the fastest EVM operations: Execution time (relative):
  • XOR: 1.0x (baseline, fastest tier)
  • AND/OR: 1.0x (same tier)
  • ADD: 1.0x (same tier)
  • MUL: 1.2x
  • DIV: 2.5x
Gas efficiency:
  • 3 gas per 256-bit XOR operation
  • ~333,333 XOR operations per million gas
  • Native hardware instruction on all platforms

References