本文主要是介绍HDLbits 刷题 --Always casez,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
学习:
Build a priority encoder for 8-bit inputs. Given an 8-bit vector, the output should report the first (least significant) bit in the vector that is 1. Report zero if the input vector has no bits that are high. For example, the input 8'b10010000 should output 3'd4, because bit[4] is first bit that is high.
From the previous exercise (always_case2), there would be 256 cases in the case statement. We can reduce this (down to 9 cases) if the case items in the case statement supported don't-care bits. This is what casez is for: It treats bits that have the value z as don't-care in the comparison.
For example, this would implement the 4-input priority encoder from the previous exercise:
always @(*) begincasez (in[3:0])4'bzzz1: out = 0; // in[3:1] can be anything4'bzz1z: out = 1;4'bz1zz: out = 2;4'b1zzz: out = 3;default: out = 0;endcase
end
A case statement behaves as though each item is checked sequentially (in reality, a big combinational logic function). Notice how there are certain inputs (e.g., 4'b1111) that will match more than one case item. The first match is chosen (so 4'b1111 matches the first item, out = 0, but not any of the later ones).
- There is also a similar casex that treats both x and z as don't-care. I don't see much purpose to using it over casez.
- The digit ? is a synonym for z. so 2'bz0 is the same as 2'b?0
It may be less error-prone to explicitly specify the priority behaviour rather than rely on the ordering of the case items. For example, the following will still behave the same way if some of the case items were reordered, because any bit pattern can only match at most one case item:
casez (in[3:0])4'bzzz1: ...4'bzz10: ...4'bz100: ...4'b1000: ...default: ...endcase
译:
构建一个处理8位输入的优先编码器。给定一个8位向量,输出应该是向量中第一个为1的位(最低有效位)。如果输入向量中没有位是高电平的,则报告0。例如,输入8'b10010000应该输出3'd4,因为第四位是第一个为高的位。
根据之前的练习(always_case2),在case语句中会有256种情况。如果case项支持不关心位(don't-care bits),我们可以将这种情况减少(至9种情况)。这就是casez的作用:它在比较时将值为z的位视为不关心位。
case语句的执行就好像是按顺序检查每个项(实际上,它是一个大型的组合逻辑函数)。请注意,某些输入(例如,4'b1111)会同时匹配多个case项。会选择第一个匹配的项(所以4'b1111匹配第一个项,输出out = 0,但不会匹配后面的任何项)。
- 还有一个类似的casex语句,它将x和z都视为不关心的值。我认为使用它而不是casez没有太多的意义。
- 问号?是z的同义词。所以2'bz0和2'b?0是相同的。
明确指定优先级行为可能比依赖于case项的顺序更不容易出错。例如,即使某些case项的顺序被重新排列,以下情况仍然会保持相同的行为,因为任何位模式最多只能匹配一个case项:
// synthesis verilog_input_version verilog_2001
module top_module (input [7:0] in,output reg [2:0] pos );always@(*) begincasez(in)8'bzzzzzzz1 : pos = 0;8'bzzzzzz1z : pos = 1;8'bzzzzz1zz : pos = 2;8'bzzzz1zzz : pos = 3;8'bzzz1zzzz : pos = 4;8'bzz1zzzzz : pos = 5;8'bz1zzzzzz : pos = 6;8'b1zzzzzzz : pos = 7;default : pos = 0;endcaseend
endmodule
运行结果:
这篇关于HDLbits 刷题 --Always casez的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!