Common relational operators (shift operator)

EDITORIAL words

The shift operators are binary operators, the operators left operand of the specified number of bits left or right, with 0 to replenish the free position. If the right-hand operand is X or Z, the result is the unknown displacement X. In applying that operators must pay attention to it this feature, it is idle bit padded with zeros, that is to say, a binary number regardless of how much of the original value, as long as has been shifted, and eventually all will become zero.

Examples of shift operator

Verilog HDL, there are two shift operators : << (logical shift left) >> and (logical right shift). Sleeper wing brothers written examples are as follows:

    /****************************************************          

    * Engineer:    Dream Brother Wing

    *   QQ               :   761664056

    * The module function: shift operator module

*****************************************************/

01  module shift(clk,rst_n,a,b);

02  input clk;

03  input rst_n;

04

05  output reg [3:0]a;

06  output reg [3:0]b;

07

08  always@(posedge clk or negedge rst_n)

09      begin

10          if(!rst_n)

11              begin

12                  a<=1;

13                  b<=4;

14              end 

15          else 

16              begin

17                  a<=(a<<1);

18                  b<=(b>>1);

19              end 

20      end 

21  endmodule

编写测试代码如下

    /****************************************************          

    *   Engineer        :   梦翼师兄

    *   QQ              :   761664056

    *   E_mail          :   [email protected]

    *   The module function:移位运算符测试模块

    *****************************************************/

01  `timescale 1ns/1ps  

02  module tb;

03  reg clk;

04  reg rst_n;

05

06  wire [3:0]a;

07  wire [3:0]b;

08

09  initial

10      begin

11          clk=0;

12          rst_n=0;

13          # 1000.1 rst_n=1;

14      end 

15      

16  always # 10 clk=~clk;   

17      

18  shift shift(

19      .clk(clk),

20      .rst_n(rst_n),

21      .a(a),

22      .b(b)

23   );

24

25  endmodule 

查看仿真波形如下

 

从仿真图,可以看出,每次a都向左边移动移位,后面补充0,直到把逻辑1溢出,后面就一直为0了。每次b都向右边移动移位,前面补充0,直到把逻辑1溢出,就一直为0了。

总结:移位运算符的使用时,左移一位可以看成是乘以2,右移一位可以看成是除以2。所以移位运算符用在计算中,代替乘法和除法。尤其是除法,使用移位的方式,可以节省资源。但使用的前提是数据位宽要进行拓展哦,不然就全部是零了。

 

Guess you like

Origin www.cnblogs.com/mengyi1989/p/11515977.html