Verilog Coding Tips and Tricks: Unary or Reduction Operators in Verilog

Saturday, October 24, 2015

Unary or Reduction Operators in Verilog

Reduction operators are those who operate on a single operand and return a single bit value. They can be summarized using the following table:


Let's see how to use these operators in a Verilog code.

reg [3:0] A;
reg B;
reg [3:0] C;
reg D;

    initial begin
        //Apply a set of inputs and wait for 100 ns.
        A = 4'b1101;  
          C = 4'b0110;  
          B = &A;     #100;  // 1 & 1 & 0 & 1 = 0
          B = ~&A;    #100;  // ~(1 & 1 & 0 & 1) = 1
          B = |A;     #100;  // 1 | 1 | 0 | 1 = 1
          B = ~|A;    #100;  // ~(1 | 1 | 0 | 1) = 0
          B = ^A;     #100;  // 1 ^ 1 ^ 0 ^  1 = 1
          B = ^~A;    #100;  // ~(1 ^ 1 ^ 0 ^  1) = 0
          B = ~^A;    #100;  // ~(1 ^ 1 ^ 0 ^  1) = 0
          D = &C;     #100;  // 0 & 1 & 1 & 0 = 0
          D = ~&C;    #100;  // ~(0 & 1 & 1 & 0) = 1
          D = |C;     #100;  // 0 | 1 | 1 | 0 = 1
          D = ~|C;    #100;  // ~(0 | 1 | 1 | 0) = 0
          D = ^C;     #100;  // 0 ^ 1 ^ 1 ^ 0 = 0
          D = ^~C;    #100;  // ~(0 ^ 1 ^ 1 ^ 0) = 1
          D = ~^C;    #100;  // ~(0 ^ 1 ^ 1 ^ 0) = 1
    end

The code is self explanatory. 
  • You can see that operator is used only on a single operand.
  • They are the unary form of bit-wise operators.
  • The particular operation is done on all the bits to get a single bit result.
  • B= &A results in the implementation of a 4 input AND gate where the inputs are the bits from operand A.
These operators can save you a lot of work in some situations. For example, to find the odd or even parity bit we can use the XNOR or XOR unary reduction operator.
 

No comments:

Post a Comment