priority encoder with 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 casez - HDLBits (01xz.net)

 1 // synthesis verilog_input_version verilog_2001
 2 module top_module (
 3     input [7:0] in,
 4     output reg [2:0] pos );
 5  always @(*)begin
 6         casez(in)
 7             8'bzzzzzzz1:pos<=3'd0;
 8             8'bzzzzzz1z:pos<=3'd1;
 9             8'bzzzzz1zz:pos<=3'd2;
10             8'bzzzz1zzz:pos<=3'd3;
11             8'bzzz1zzzz:pos<=3'd4;
12             8'bzz1zzzzz:pos<=3'd5;
13             8'bz1zzzzzz:pos<=3'd6;
14             8'b1zzzzzzz:pos<=3'd7;   /*后部可以编写为0,也可以写为z,
15             还是<=这个符号使用的习惯问题*/
16             default:pos<=3'd0;
17         endcase
18     end
19 
20 endmodule

 再写:

你还是那么的爱写非阻塞……

module top_module (
    input [7:0] in,
    output reg [2:0] pos );
	always@*begin
        casez(in)
        	8'bzzzzzzz1:pos=0;
            8'bzzzzzz10:pos=1;
            8'bzzzzz100:pos=2;
            8'bzzzz1000:pos=3;
            8'bzzz10000:pos=4;
            8'bzz100000:pos=5;
            8'bz1000000:pos=6;
            8'b10000000:pos=7;
            default:pos=0;
        endcase
    end
endmodule

  

posted @ 2023-04-20 09:58  江左子固  阅读(39)  评论(0)    收藏  举报