0
0
VerilogHow-ToBeginner · 3 min read

How to Model XOR Gate in Verilog: Syntax and Example

To model an xor gate in Verilog, use the assign statement with the ^ operator for bitwise XOR. For example, assign out = a ^ b; creates an XOR gate output from inputs a and b.
📐

Syntax

The basic syntax to model an XOR gate in Verilog uses the assign keyword followed by the output signal, an equals sign, and the XOR operator ^ applied to input signals.

  • assign: keyword to create continuous assignment.
  • out: output wire that holds the XOR result.
  • a ^ b: bitwise XOR operation between inputs a and b.
verilog
assign out = a ^ b;
💻

Example

This example shows a simple module named xor_gate that takes two inputs a and b and produces an output out which is the XOR of the inputs.

verilog
module xor_gate(
    input wire a,
    input wire b,
    output wire out
);

assign out = a ^ b;

endmodule
⚠️

Common Pitfalls

Common mistakes when modeling XOR gates in Verilog include:

  • Using & (AND) or | (OR) instead of ^ (XOR) operator.
  • Forgetting to declare output as wire or using reg incorrectly for continuous assignments.
  • Trying to use assign inside procedural blocks like always, which is not allowed.

Correct usage is a continuous assignment outside procedural blocks.

verilog
/* Wrong way: Using AND instead of XOR */
assign out = a & b;  // Incorrect for XOR

/* Right way: Using XOR operator */
assign out = a ^ b;  // Correct
📊

Quick Reference

ConceptVerilog SyntaxDescription
XOR operator^Bitwise exclusive OR between inputs
Continuous assignmentassign out = a ^ b;Assigns XOR result to output wire
Module portsinput wire a, b; output wire out;Declare inputs and output signals
Module definitionmodule name(...); ... endmoduleDefines a reusable hardware block

Key Takeaways

Use the ^ operator with assign to model XOR gates in Verilog.
Declare outputs as wire for continuous assignments.
Do not use assign inside procedural blocks like always.
XOR gate outputs 1 only when inputs differ.
Keep syntax simple: assign out = a ^ b;