Menu
Coddy logo textTech

XOR XNOR Gates

Part of the Fundamentals section of Coddy's Verilog journey — lesson 41 of 90.

This lesson covers two additional logic gates: XOR (exclusive OR) and XNOR (exclusive NOR). These gates are useful for comparing bits and parity checking.

XOR Gate

The XOR gate outputs 1 when the inputs are different.

Truth Table (2-input):

about
000
011
101
110

Verilog gate primitive:

xor(out, a, b);

Continuous assignment equivalent:

assign out = a ^ b;

XNOR Gate

The XNOR gate outputs 1 when the inputs are the same. It is the opposite of XOR.

Truth Table (2-input):

about
001
010
100
111

Verilog gate primitive:

xnor(out, a, b);

Continuous assignment equivalent:

assign out = a ~^ b;   // or ~(a ^ b)

Multiple Inputs

XOR and XNOR gates can have more than 2 inputs. The output is:

  • XOR: 1 if an odd number of inputs are 1
  • XNOR: 1 if an even number of inputs are 1
xor(out, a, b, c);      // 3-input XOR
xnor(out, p, q, r, s);  // 4-input XNOR

Example (3-input XOR):

abcout
0000
0011
0101
0110
1001
1010
1100
1111

Common Uses

UseExample
Compare if two bits are differentxor(diff, a, b)
Compare if two bits are the samexnor(same, a, b)
Parity generation (odd number of 1's)xor(parity, data[0], data[1], data[2], data[3])
Parity checking (even number of 1's)xnor(parity, data[0], data[1], data[2], data[3])

Code Example

module xor_xnor_demo (
  input a, b,
  output xor_out,
  output xnor_out
);
  xor(xor_out, a, b);
  xnor(xnor_out, a, b);
endmodule

Summary Table

GateOutput 1 whenPrimitiveOperator
XORInputs are differentxor(out, a, b)^
XNORInputs are the samexnor(out, a, b)~^
challenge icon

Challenge

Add the missing gate primitives based on the tasks.

What to do:

  1. Create an XOR gate with output xor_result and inputs x and y
  2. Create an XNOR gate with output xnor_result and inputs x and y

Cheat sheet

XOR outputs 1 when inputs are different. XNOR outputs 1 when inputs are the same.

GateOutput 1 whenPrimitiveOperator
XORInputs are differentxor(out, a, b)^
XNORInputs are the samexnor(out, a, b)~^

For multiple inputs: XOR outputs 1 if an odd number of inputs are 1; XNOR outputs 1 if an even number of inputs are 1.

xor(out, a, b, c);      // 3-input XOR
xnor(out, p, q, r, s);  // 4-input XNOR

Try it yourself

module xor_xnor_challenge (
  input x,
  input y,
  output xor_result,
  output xnor_result
);
  
  // TODO: Add XOR gate (xor_result = x ^ y)
  
  // TODO: Add XNOR gate (xnor_result = x ~^ y)

endmodule
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals