HDLBits练习Shift18 Verilog逻辑右移和算数右移的区别

算术右移时,移入的是移位寄存器中数字(本例中为 q[63])的符号位,而不是逻辑右移时的零。右移n位,即加入n位符号位。即若符号位为1,在左边补1;若符号位为0,就补0。

算术右移的另一种思路是,它假定被移位的数字是带符号的,并保留符号,因此算术右移是右移n位将带符号的数字除以 2 的n次幂。

算数左移和逻辑左移的结果并无差别。算​术左移和逻辑左移一样都是右边补0。

Build a 64-bit arithmetic shift register, with synchronous load. The shifter can shift both left and right, and by 1 or 8 bit positions, selected by amount.

An arithmetic right shift shifts in the sign bit of the number in the shift register (q[63] in this case) instead of zero as done by a logical right shift. Another way of thinking about an arithmetic right shift is that it assumes the number being shifted is signed and preserves the sign, so that arithmetic right shift divides a signed number by a power of two.

There is no difference between logical and arithmetic left shifts.

  • load: Loads shift register with data[63:0] instead of shifting.
  • ena: Chooses whether to shift.
  • amount: Chooses which direction and how much to shift.
    • 2'b00: shift left by 1 bit.
    • 2'b01: shift left by 8 bits.
    • 2'b10: shift right by 1 bit.
    • 2'b11: shift right by 8 bits.
  • q: The contents of the shifter.
module top_module(
    input clk,
    input load,
    input ena,
    input [1:0] amount,
    input [63:0] data,
    output reg [63:0] q); 
    always@(posedge clk)
        begin
            if(load)
                q<=data;
            else if(ena)
                begin
                    case(amount)
                        2'b00:q<={q[62:0],1'b0};
                        2'b01:q<={q[55:0],8'b0};
                        2'b10:q<={q[63],q[63:1]};
                        2'b11:q<={{8{q[63]}},q[63:8]};
                        default:q<=q;
                    endcase
                end
           end           
endmodule

补充:

或可以直接定义q为有符号数定义signed,可直接用移位符

module top_module(
    input clk,
    input load,
    input ena,
    input [1:0] amount,
    input [63:0] data,
    output reg signed [63:0] q); 
    always@(posedge clk)
        begin
            if(load)
                q<=data;
            else if(ena)
                begin
                    case(amount)
                        2'b00:q<=q<<1;
                        2'b01:q<=q<<8;
                        2'b10:q<=q>>>1;
                        2'b11:q<=q>>>8;
                        default:q<=q;
                    endcase
                end
           end           
endmodule

                    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值