题解 | #移位运算与乘法#
移位运算与乘法
http://www.nowcoder.com/practice/1dd22852bcac42ce8f781737f84a3272
`timescale 1ns/1ns
module multi_sel(
input [7:0]d ,
input clk,
input rst,
output reg input_grant,
output reg [10:0]out
);
reg [7:0] d1;
always @(posedge clk or negedge rst) begin
if(~rst) begin
per_cnt <= 2'b0;
end else begin
if (per_cnt==2'b11) begin
per_cnt <= 2'b0;
end else begin
per_cnt <= per_cnt + 1'b1;
end
end
end
always @(posedge clk or negedge rst) begin
if(~rst) begin
input_grant <= 1'b0;
end else begin
if (per_cnt==2'b0) begin
input_grant <= 1;
end else begin
input_grant <= 0;
end
end
end
//需要存一下d
always @(posedge clk or negedge rst) begin
if(~rst) d1 <= 'b0;
else if(per_cnt==2'b0) d1 <= d;
else if(per_cnt==2'b11) d1 <= 'b0;
end
always @(posedge clk or negedge rst) begin
if (~rst) begin
out <= 'b0;
end else begin
case (per_cnt)
2'd0: out <= d;
2'd1: out <= (d1<<2) - d1;
2'd2: out <= (d1<<3) - d1;
2'd3: out <= (d1<<3);
endcase
end
end
//*************code***********//
endmodule
module multi_sel(
input [7:0]d ,
input clk,
input rst,
output reg input_grant,
output reg [10:0]out
);
//*************code***********//
//这题易错点很多:首先input_grant的赋值我看错了,一开始写成0和3的时候使能;其次移位运算和减法优先级的问题没注意,以后一定先写括号;再者要用d1存一下输入的数据,这块看报错的波形看出来了
reg [1:0] per_cnt;reg [7:0] d1;
always @(posedge clk or negedge rst) begin
if(~rst) begin
per_cnt <= 2'b0;
end else begin
if (per_cnt==2'b11) begin
per_cnt <= 2'b0;
end else begin
per_cnt <= per_cnt + 1'b1;
end
end
end
always @(posedge clk or negedge rst) begin
if(~rst) begin
input_grant <= 1'b0;
end else begin
if (per_cnt==2'b0) begin
input_grant <= 1;
end else begin
input_grant <= 0;
end
end
end
//需要存一下d
always @(posedge clk or negedge rst) begin
if(~rst) d1 <= 'b0;
else if(per_cnt==2'b0) d1 <= d;
else if(per_cnt==2'b11) d1 <= 'b0;
end
always @(posedge clk or negedge rst) begin
if (~rst) begin
out <= 'b0;
end else begin
case (per_cnt)
2'd0: out <= d;
2'd1: out <= (d1<<2) - d1;
2'd2: out <= (d1<<3) - d1;
2'd3: out <= (d1<<3);
endcase
end
end
//*************code***********//
endmodule