Verilog学习笔记 HDLBits——More Verilog Features

本文介绍了Verilog的高级特性,包括条件运算符用于选择电路路径,位宽缩减运算符实现奇偶校验,以及如何使用for循环和generate语句构建大规模组合逻辑电路,如位反转、位计数和加法器。通过实例展示了如何利用这些特性设计高效简洁的Verilog代码。

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

Verilog有一个三元条件运算符(?😃

(condition ? if_true : if_false)
这可以用于在一行中根据条件(a mux!)从两个值中选择一个,而不用在组合always块中使用if-then。

Examples:

(0 ? 3 : 5) .
(sel ? b : a)

always @(posedge clk)
q <= toggle ? ~q : q;

always @(*) //
case (state)
A: next = w ? B : A;
B: next = w ? A : B;
endcase

一、More Verilog Features

1.Conditional ternary operator

Practice: Given four unsigned numbers, find the minimum. Unsigned numbers can be compared with standard comparison operators (a < b). Use the conditional operator to make two-way min circuits, then compose a few of them to create a 4-way min circuit. You’ll probably want some wire vectors for the intermediate results.right?..)
翻译:给定四个无符号数,求最小值。无符号数可以与标准的比较运算符进行比较(a <b).用条件运算符构造双向最小电路,再组合几个组成4路最小电路。你可能需要一些wire作为中间结果。

Solution(不唯一,仅供参考):

module top_module (
    input [7:0] a, b, c, d,
    output [7:0] min);//
    wire [7:0]min_ab,min_cd;
    assign min_ab = a>b?b:a;
    assign min_cd = c>d?d:c;
    assign min = min_ab>min_cd?min_cd:min_ab;

endmodule


Timing Diagram
在这里插入图片描述

2.Reduction operators

Practice:Create a circuit that will compute a parity bit for a 8-bit byte (which will add a 9th bit to the byte). We will use “even” parity, where the parity bit is just the XOR of all 8 data bits.
翻译:创建一个电路,将计算一个8位字节的奇偶校验位(这将增加第9位的字节)。我们将使用“偶”奇偶校验,其中奇偶校验位就是所有8个数据位的异或。
奇偶校验:通过检验位将传输1的个数变成奇数就是奇校验,变成偶数就是偶校验。

Solution(不唯一,仅供参考):

module top_module (
    input [7:0] in,
    output parity); 
	assign parity = ^in;
endmodule

小知识
上述代码中用到了“归纳运算符”,当我们需要对一个向量的所有位进行操作时,如 a[0]&a[1]&a[2]&a[3]…,但这对于长的标量来说,编写代码会比较的麻烦,所以可以使用归纳运算符a[0]&a[1]&a[2]&a[3]…&a[100]=%a;理还有 &,|,~^,例如:

&a [30] // AND:a[3]&a[2]&a[1]&a[0]
|b [30] // OR: b[3]|b[2]|b[1]|b[0]
^c [20] // XOR:c[2]^c[1]^c[0]

“!”表示逻辑取反,“~”表示按位取反。举一个例子让你更好的记住它们的区别:
!(1100)=0;
~(1100)=0011

3.Reduction:Even wider gates

Practice:Build a combinational circuit with 100 inputs, in[99:0].
翻译:建立100输入的与门、或门和异或门(和上题一样)。

Solution(不唯一,仅供参考):

module top_module( 
    input [99:0] in,
    output out_and,
    output out_or,
    output out_xor 
);
	assign out_and = &in;
    assign out_or = |in;
    assign out_xor = ^in;
endmodule

Timing Diagram
在这里插入图片描述
在这里插入图片描述

4.Combinational for-loop:Vector reversal 2

Practice:Given a 100-bit input vector [99:0], reverse its bit ordering.
翻译:给定一个100位的输入向量[99:0],反转它的位顺序。

Solution(不唯一,仅供参考):

module top_module( 
    input [99:0] in
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值