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.
前言
五个输入,包括一个时钟clk,一个载入信号load,一个使能信号ena,一个移位数量选择信号amount,一个输入信号data;一个输出信号q。
代码
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<<1;
2'b01:q<=q<<8;
2'b10:q<={q[63],q[63:1]};
2'b11:q<={{8{q[63]}},q[63:8]};
default:q<=q;
endcase
end
else q<=q;
end
endmodule
总结
左移就是把后面的变量往前面放,右移就是把前面的数往后面放,算数移位的左移与逻辑左移一致,但是算数右移需要保持符号位不变,因此不能用移位符直接操作,需要保留q[63],将逻辑移位的{1’b0, q[63:1]}变为{q[63], q[63:1]},其中8位算数右移包含了拼接符的套用。