7. XOR Gate

module top_module(input a, input b, output y);
  assign y = a ^ b;
endmodule

💡 Remember

  • The ^ operator in Verilog performs bitwise XOR.
  • Output is 1 only when inputs differ (a=0,b=1 or a=1,b=0).
  • Synthesizes to a single XOR gate in hardware.

Testbench Code

`timescale 1ns/1ps

module tb;
  // Inputs
  reg a, b;
  // Outputs
  wire y;
  // Expected Outputs
  reg expected_y;

  // Mismatch signal
  wire mismatch = (y !== expected_y);

  // DUT
  top_module dut(.a(a), .b(b), .y(y));

  integer TOTAL, PASS, FAIL, i;
  initial begin
    $dumpfile("tb.vcd");
    $dumpvars(0, tb.a, tb.b, tb.y, tb.expected_y, tb.mismatch);

    TOTAL=0; PASS=0; FAIL=0;

    for (i=0; i<4; i=i+1) begin
      {a,b} = i[1:0];
      expected_y = a ^ b;
      #5;
      TOTAL++;
      if (!mismatch) PASS++; else FAIL++;
      $display("a=%b b=%b | y=%b | expected_y=%b | mismatch=%b",
               a, b, y, expected_y, mismatch);
    end

    $display("======================================");
    $display("TOTAL_TEST_CASES=%0d", TOTAL);
    $display("TOTAL_PASSED_TEST_CASES=%0d", PASS);
    $display("TOTAL_FAILED_TEST_CASES=%0d", FAIL);
    $display("ALL_TEST_CASES_PASSED=%s", (FAIL==0) ? "true" : "false");
    $display("======================================");
    $finish;
  end
endmodule