学习:
You're already familiar with bitwise operations between two values, e.g., a & b or a ^ b. Sometimes, you want to create a wide gate that operates on all of the bits of one vector, like (a[0] & a[1] & a[2] & a[3] ... ), which gets tedious if the vector is long.
The reduction operators can do AND, OR, and XOR of the bits of a vector, producing one bit of output:
& a[3:0] // AND: a[3]&a[2]&a[1]&a[0]. Equivalent to (a[3:0] == 4'hf) | b[3:0] // OR: b[3]|b[2]|b[1]|b[0]. Equivalent to (b[3:0] != 4'h0) ^ c[2:0] // XOR: c[2]^c[1]^c[0]
These are unary operators that have only one operand (similar to the NOT operators ! and ~). You can also invert the outputs of these to create NAND, NOR, and XNOR gates, e.g., (~& d[7:0]).
Now you can revisit 4-input gates and 100-input gates.
译:
你已经熟悉了两个值之间的位操作,例如 a & b
或 a ^ b
。有时,你想要创建一个宽门电路,它对一个向量的所有位进行操作,如 (a[0] & a[1] & a[2] & a[3] ... )
,如果这个向量很长,这样做会非常繁琐。
归约操作符可以对一个向量的位进行AND、OR和XOR操作,产生一个位的输出结果。
这些是只有单一操作数的一元操作符(类似于NOT操作符!和~)。你也可以反转这些操作的结果来创建NAND、NOR和XNOR门,例如,(~& d[7:0])。
练习:
Parity checking is often used as a simple method of detecting errors when transmitting data through an imperfect channel. 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个数据位的异或(XOR)结果。
module top_module (
input [7:0] in,
output parity);
assign parity = ^in[7:0];
endmodule
代码解释:
-
assign parity = ^in[7:0];
:这是一个连续赋值语句,使用assign
关键字。它将in
向量的所有位进行按位取反的异或(XOR)操作,并将结果赋值给parity
。在Verilog中,^
操作符用于执行按位异或操作。由于in
是一个8位向量,^in[7:0]
实际上是对in
中的每一位执行取反操作,然后对这些取反后的位进行异或。- 如果
in
中的数据位数量是偶数,那么异或结果将是0,表示偶校验位为0。 - 如果
in
中的数据位数量是奇数,那么异或结果将是1,表示偶校验位为1。
- 如果
运行结果: