前言
这是我第二次刷HDLBits的题,第一次是刚接触FPGA时,为了快速入门Verilog,第一次刷题跟着B站视频刷的,但是现在发现没有很大的用处,个人感觉还是有一点Verilog基础后,再来刷HDLBits会好一点,虽然很多人说这上面的题都很简单,但是还是值得刷一遍,里面几乎涵盖了Verilog的所有常用语法,并且还可以尝试用不同方法解同一道题。
代码以下是我写的每道题的代码和思路
选择器注意;
- 最后一个多比特输入中选择多比特输出,要选择其中某几位,这个时候要使用
in[低位+:低位要加的步长]
,或者可以使用拼接符
// 单bit,2选1选择器
// 三目条件判断
module top_module(
input a, b, sel,
output out );
assign out = sel ? b : a ;
endmodule
// 多bit,2选1选择器
module top_module(
input [99:0] a, b,
input sel,
output [99:0] out );
assign out = sel ? b : a;
endmodule
// 多bit,9选1选择器
// case语句
module top_module(
input [15:0] a, b, c, d, e, f, g, h, i,
input [3:0] sel,
output [15:0] out );
always @(*) begin
case (sel)
4'd0: out = a;
4'd1: out = b;
4'd2: out = c;
4'd3: out = d;
4'd4: out = e;
4'd5: out = f;
4'd6: out = g;
4'd7: out = h;
4'd8: out = i;
default: out = 16'hffff;
endcase
end
endmodule
module top_module(
input [255:0] in,
input [7:0] sel,
output out );
assign out = in[sel];
endmodule
// 选择向量中某几位
module top_module(
input [1023:0] in,
input [7:0] sel,
output [3:0] out );
//方法一
assign out = in[4*sel+:4];//片选多个比特位
//方法二
assign out = {in[4*sel+3],in[4*sel+2],in[4*sel+1],in[4*sel+0]};
endmodule