Verilog刷题笔记22

题目:
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.
Verilog刷题笔记22_第1张图片
解题:

module top_module (
    input [7:0] in,
    output reg [2:0] pos );

    always@(*)begin
        casez(in)
            8'bzzzzzzz1:pos=3'b000;
            8'bzzzzzz1z:pos=3'b001;
            8'bzzzzz1zz:pos=3'b010;
            8'bzzzz1zzz:pos=3'b011;
            8'bzzz1zzzz:pos=3'b100;
            8'bzz1zzzzz:pos=3'b101;
            8'bz1zzzzzz:pos=3'b110;
            8'b1zzzzzzz:pos=3'b111;
            default:pos=3'b000;
        endcase
    end

endmodule

结果正确:
Verilog刷题笔记22_第2张图片
注意点:
显式指定优先级行为,而不是依赖于案例项的排序,可能不太容易出错。例如,如果对某些事例项进行了重新排序,则以下操作仍将以相同的方式进行,因为任何位模式最多只能匹配一个事例项:

casez (in[3:0])
    4'bzzz1: ...
    4'bzz10: ...
    4'bz100: ...
    4'b1000: ...
    default: ...
endcase

你可能感兴趣的:(笔记)