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

Bitwise operations provide low-level bit manipulation on 256-bit (32-byte) values. These operations enable efficient masking, flag management, and bit-level data packing critical for optimized smart contract implementations. 8 opcodes enable:
  • Logical operations: AND, OR, XOR, NOT
  • Byte extraction: BYTE
  • Shift operations (EIP-145): SHL, SHR, SAR
All operations work on unsigned 256-bit integers, with shift operations introduced in the Constantinople hardfork (EIP-145).

Opcodes

Bit Manipulation Patterns

Masking

Extract specific bits using AND:

Flag Management

Use individual bits as boolean flags:

Data Packing

Pack multiple values into single uint256:

Shift Operations (EIP-145)

EIP-145 Background

Before Constantinople (pre-EIP-145), shift operations required expensive arithmetic:
  • Left shift: value * 2^shift (MUL + EXP)
  • Right shift: value / 2^shift (DIV + EXP)
EIP-145 introduced native shift opcodes (SHL, SHR, SAR) at 3 gas each, making shifts as cheap as basic arithmetic.

Shift Direction

Stack order matters:

Logical vs Arithmetic Shifts

SHR (Logical Shift Right):
  • Shifts bits right, filling with zeros
  • Unsigned operation
  • Divides by powers of 2
SAR (Arithmetic Shift Right):
  • Shifts bits right, preserving sign bit
  • Signed operation (two’s complement)
  • Divides signed integers by powers of 2

Overflow Behavior

Shifts >= 256 bits have defined behavior:

Common Patterns

Efficient Multiplication/Division by Powers of 2

Extract Address from uint256

Check if Power of 2

Count Set Bits (Hamming Weight)

Bit Reversal

Zero/One Extension

Gas Costs

All bitwise operations cost 3 gas (GasFastestStep): Comparison with arithmetic:
  • Bitwise ops: 3 gas
  • ADD/SUB: 3 gas
  • MUL/DIV/MOD: 5 gas
  • Shifts replace expensive MUL/EXP or DIV/EXP combinations (5-60+ gas → 3 gas)

Edge Cases

Maximum Values

Zero Inputs

Byte Extraction

Shift Edge Cases

Implementation

TypeScript

Zig

Security Considerations

Off-by-One Errors

Bit indexing is zero-based and left-to-right (MSB to LSB):

Mask Construction

Incorrect masks can leak unintended bits:

Shift Amount Validation

Sign Extension Pitfalls

SAR treats MSB as sign bit. Ensure values are properly signed:

Benchmarks

Bitwise operations are among the fastest EVM operations: EIP-145 impact:
  • Pre-Constantinople: Left shift = MUL + EXP = 5 + (10 + 50/byte) gas
  • Post-Constantinople: SHL = 3 gas
  • Savings: 12-1607 gas per shift operation

References