shift operators in verilog


Verilog provides a left shift operator using << to shift the bits to the left. You can specify the number of bits that need to shift. See the following example


  1. // referencedesigner.com
  2. // Example showing use of left shift << and right shift >>
  3.  
  4. module test;
  5.  
  6. reg[3:0] x;
  7.  
  8. initial
  9. begin
  10. x =4'b1100;
  11. $display("x before shift = %4b",x);
  12. x = x<<2;
  13. $display("x after shift = %4b",x);
  14. end
  15.  
  16. endmodule


The statement

x = x<<2;


shifts x by two places to the left. This example gives the following output
x before shift = 1100
x after shift = 0000

The LSB bits are padded with 0s after the shift.

The >> is used to shift the bits to the right. The MSB bits are padded with 0s after the shift.

As an example in

x = 4'b1100;
x  = x>>1;


The value of x after the two statements is 0'b0110.

The left shift by one place can be interpreted as multiplication by 2. The left shift by 2 places means multiplication by 4.

An important consideration in left shift is that the bits are lost as we saw in the example below. But, if the variable on the left side of the assignment statement is wider than the variable on the right side of the assignment, the value may be preserved. See the following example.




  1. module test;
  2.  
  3. reg[3:0] x;
  4. reg[5:0] y;
  5.  
  6. initial
  7. begin
  8. x =4'b1100;
  9. $display("x before shift = %4b",x);
  10. y = x<<2;
  11. $display("y after shift = %6b",y);
  12. end
  13.  
  14. endmodule
  15.  


The output in this case is
x before shift = 1100
y after shift = 110000
However, this does not apply in case of right shift operator, where the bits shifted out of the right side are not required to be preseved. Hence the code

  1. module test;
  2.  
  3. reg[3:0] x;
  4. reg[5:0] y;
  5.  
  6. initial
  7. begin
  8. x =4'b1100;
  9. $display("x before shift = %4b",x);
  10. y = x>>3;
  11. $display("y after shift = %6b",y);
  12. end
  13.  
  14. endmodule
  15.  


produces no surprise and output is

 
x before shift = 1100
y after shift = 000001


The least significant bits in case of right shift operator are always lost.

Synthesis tools may choose to apply this consideration of unequal widths of the operand on the left side of left shift operator.