Prev Problem
Next Problem

12. Vector Bitwise Operators

Back To All Submissions
Previous Submission
Next Submission

Solving Approach

How do you plan to solve it?

Bitwise operators (&, |, ^, ~^) in Verilog operate on vectors (single-bit or multi-bit). The operation is applied bit-by-bit across corresponding bit positions of the operands. For correct evaluation, both operands should have the same bit-width (otherwise Verilog will perform padding or truncation, which may lead to unintended results).
Eg: Inputs:

  • A[3:0] (4-bit)
  • B[1:0] (4-bit)

Outputs:

  • AND_OUT[3:0] = bitwise AND of A and B

Expected Behavior (example)

        A = 4'b1010;   // decimal 10
        B = 2'b11;     // decimal 3

Verilog automatically pads B with zeros on the left to match the width of A.
So internally, B becomes 0011.
Thus,
   A = 1010
   B = 0011   (zero-padded)
---------------
AND_OUT = 0010
 

 

Code

module bitwise_ops_demo (
    input wire [3:0]  A,
    input wire [3:0]  B,
    output wire [3:0] AND_OUT,
    output wire [3:0] OR_OUT,
    output wire [3:0] XOR_OUT,
    output wire [3:0] XNOR_OUT
);

    assign AND_OUT  = A & B;
    assign OR_OUT   = A | B;
    assign XOR_OUT  = A ^ B;
    assign XNOR_OUT = ~(A ^ B);

endmodule

 

Was this helpful?
Upvote
Downvote