In this track: Inside the EVM
advanced · 4 MIN READ

Bitwise AND, OR and XOR

These operations combine corresponding bits across words.

LET’S PICTURE IT

A transparent stencil can retain, combine or highlight selected positions.

SEE IT FOR YOURSELF
Watch a stack machine execute a tiny programStep 1 / 4
Watch a stack machine execute a tiny programProgram→ PUSH1 0x02PUSH1 0x03ADD · STOPStackEmptyPC = 0A fixed local model; not a complete EVM implementationPUSH1 0x02Push immediate 2Next PC = 2Stack · top first2PUSH1 occupies one opcode byte plus one immediate bytePUSH1 0x03Push immediate 3Next PC = 4Stack · top first32The first value is below the most recently pushed valueADD3 + 2 = 5Next: STOP at PC 5Stack5No automatic SSTOREStack, memory and persistent storage are different locations

The program bytes are PUSH1 02, PUSH1 03, ADD, STOP. The program counter begins at byte zero.

Animated local teaching model. No wallet, RPC or live blockchain data. Some labels and hashes are abbreviated for readability.

Use AND as a mask

AND retains a bit only where both inputs have that bit set. Masking with 0xff keeps the low eight bits and clears the higher bits.

Use OR to combine fields

OR sets a bit where either input has it set. When combining packed fields, ensure the intended regions do not overlap accidentally.

Use XOR for differences

XOR sets a bit where the two input bits differ. Applying the same XOR mask twice restores the original bit pattern.

Separate bit operations from booleans

These are full-word bitwise operations. A Solidity boolean expression and a word mask may use related instructions but have different type-level meaning.

Trace the idea

0x1234 AND 0x00ff = 0x0034
0x1200 OR 0x0034 = 0x1234
0x1234 XOR 0x00ff = 0x12cb

Stack examples list the bottom first and the top last. These small traces omit gas and surrounding dispatch unless stated.

QUICK CHECK · NO PRESSURE

What does AND with 0xff retain?

Your progress stays in this browser.
Keep exploring the original referenceethereum.org ↗

Original explanations by EtherTools. Examples are educational and source-linked; this site is independent of the Ethereum Foundation. Our approach.