HDLbits 刷题 -- Always case

学习:

        Case statements in Verilog are nearly equivalent to a sequence of if-elseif-else that compares one expression to a list of others. Its syntax and functionality differs from the switch statement in C.

always @(*) begin     // This is a combinational circuit
    case (in)
      1'b1: begin 
               out = 1'b1;  // begin-end if >1 statement
            end
      1'b0: out = 1'b0;
      default: out = 1'bx;
    endcase
end
  • The case statement begins with case and each "case item" ends with a colon. There is no "switch".
  • Each case item can execute exactly one statement. This makes the "break" used in C unnecessary. But this means that if you need more than one statement, you must use begin ... end.
  • Duplicate (and partially overlapping) case items are permitted. The first one that matches is used. C does not allow duplicate case items.

译:在Verilog中,case语句几乎等同于一系列比较一个表达式与一系列其他表达式的if-elseif-else。它的语法和功能与C语言中的switch语句不同。

        case语句以case开头,每个“case项”以冒号结束。没有使用“switch”关键字。
        每个case项可以执行一个精确的语句。这使得C语言中使用的“break”变得不必要。但这同时也意味着,如果你需要执行多于一个语句,你必须使用begin ... end结构。
        允许存在重复(以及部分重叠的)case项。匹配的第一个case项会被使用。C语言不允许有重复的case项。

练习:

Case statements are more convenient than if statements if there are a large number of cases. So, in this exercise, create a 6-to-1 multiplexer. When sel is between 0 and 5, choose the corresponding data input. Otherwise, output 0. The data inputs and outputs are all 4 bits wide.

如果存在大量情况,case语句比if语句更方便。因此,在这个练习中,创建一个6到1的多路选择器。当选择信号sel在0到5之间时,选择相应的数据输入。否则,输出0。数据输入和输出都是4位宽。

// synthesis verilog_input_version verilog_2001
module top_module ( 
    input [2:0] sel, 
    input [3:0] data0,
    input [3:0] data1,
    input [3:0] data2,
    input [3:0] data3,
    input [3:0] data4,
    input [3:0] data5,
    output reg [3:0] out   );

    always@(*) begin  // This is a combinational circuit
        case(sel) 
            3'b000:   out[3:0] = data0[3:0];
            3'b001:   out[3:0] = data1[3:0];
            3'b010:   out[3:0] = data2[3:0];
            3'b011:   out[3:0] = data3[3:0];
            3'b100:   out[3:0] = data4[3:0];
            3'b101:   out[3:0] = data5[3:0];
            default :   out = 4'b0;
        endcase
    end
            

endmodule

运行结果:

        

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刚及格的陆拾伍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值