Bit-wise Operators – Verilog Example

The Verilog bitwise operators are used to perform a bit-by-bit operation on two inputs. They produce a single output. They take each bit individually and perform a boolean algebra operation with the other input. The table of bit wise operators is shown below:

Operator Type
& And
~& Nand
| Or
~| Nor
^ Xor
~^ Xnor

Refer to this page for a refresher on what each of these truth tables looks like.

The bitwise operators above can operate on either scalars (single bit inputs) or vectors (multiple bit inputs). If one input is not as long as the other, it will automatically be left-extended with zeros to match the length of the other input.

If you only want to operate on the bits of a single input vector, then you are likely looking for the reduction operator. If you are looking to test for equality in an if statement, you should check out how to use logical operators. It is important to understand the difference between these three as they are very similar and are often confused.

Below is the console output from running the code below in Modelsim:

# AND of 1 and 0 is 0
# OR  of 1 and 0 is 1
# XOR of 1 and 0 is 1
# NOT of 1 is 0
# AND of 0101 and 1100 is 0100
# OR  of 0101 and 1100 is 1101
# XOR of 0101 and 1100 is 1001
# NOT of 0101 is 1010



bitwise_operators.v:

module bitwise_operators ();

  reg r_A = 1'b1;
  reg r_B = 1'b0;

  reg [3:0] r_X = 4'b0101;
  reg [3:0] r_Y = 4'b1100;
  wire [3:0] w_AND_VECTOR, w_OR_VECTOR, w_XOR_VECTOR, w_NOT_VECTOR;
  
  assign w_AND_SCALAR = r_A & r_B;
  assign w_OR_SCALAR  = r_A | r_B;
  assign w_XOR_SCALAR = r_A ^ r_B;
  assign w_NOT_SCALAR = ~r_A;

  assign w_AND_VECTOR = r_X & r_Y;
  assign w_OR_VECTOR  = r_X | r_Y;
  assign w_XOR_VECTOR = r_X ^ r_Y;
  assign w_NOT_VECTOR = ~r_X;
  
  // Initial statement is not synthesizable (test code only)
  initial
    begin
      #10;
      // Scalar Tests:
      $display("AND of 1 and 0 is %b", w_AND_SCALAR);
      $display("OR  of 1 and 0 is %b", w_OR_SCALAR);
      $display("XOR of 1 and 0 is %b", w_XOR_SCALAR);
      $display("NOT of 1 is %b", w_NOT_SCALAR);
      #10;
      // Vector Tests: (bit by bit comparison)
      $display("AND of 0101 and 1100 is %b", w_AND_VECTOR);
      $display("OR  of 0101 and 1100 is %b", w_OR_VECTOR);
      $display("XOR of 0101 and 1100 is %b", w_XOR_VECTOR);
      $display("NOT of 0101 is %b", w_NOT_VECTOR);
    end
endmodule // bitwise_operators

Learn Verilog

Modules

Learn VHDL