verilog的if語句與case對比(判斷一個數字所在的范圍)


踏破鐵鞋無覓處,得來全不費功夫啊

當想要判斷一個數在不在一個范圍內的話如果用普通的case實現是不太現實的,總不能把所有的范圍內的數字都列出來吧,但是如果采用casez或者casex 語句就很簡單了,不得不為自己的孤陋寡聞汗顏。

1先用簡單的if else來實現的話

代碼

`timescale 1ns / 1ps
module not_0if(input [20:0]ampout,
             input clk,syn_rst,en,
                 output reg[4:0] m);
parameter A=21'b1_0000_0000_0000_0000_0000;
always@(posedge clk or negedge syn_rst)
begin
    if(~syn_rst)
    begin
        m<=0;
    end
    else
    begin
    if(en)begin
        if(ampout>A)
        m <= 20;
        else if(ampout>(A>>1))
        m <= 19;
        else if(ampout>(A>>2))
        m <= 18;
        else if(ampout>(A>>3))
        m <= 17;
        else if(ampout>(A>>4))
        m <= 16;
        else if(ampout>(A>>5))
        m <= 15;
        else if(ampout>(A>>6))
        m <= 14;
        else if(ampout>(A>>7))
        m <= 13;
        else if(ampout>(A>>8))
        m <= 12;
        else if(ampout>(A>>9))
        m <= 11;
        else if(ampout>(A>>10))
        m <= 10;
        else if(ampout>(A>>11))
        m <= 9;
        else if(ampout>(A>>12))
        m <= 8;
        else if(ampout>(A>>13))
        m <= 7;
        else if(ampout>(A>>14))
        m <= 6;
        else if(ampout>(A>>15))
        m <= 5;
        end
        
    end
end 
endmodule 

 

仿真

資源占用

2再用casez實現

代碼

`timescale 1ns / 1ps
module not_0(input [20:0]ampout,
             input clk,syn_rst,en,
                 output reg[4:0] m);
always@(posedge clk or negedge syn_rst)
begin
    if(~syn_rst)
    begin
        m<= 5'dz;
    end
    else 
    begin
    if(en)
        casez(ampout)
            21'b1????_????_????_????_????: m<='d20;
            21'b01???_????_????_????_????: m<='d19;
            21'b001??_????_????_????_????: m<='d18;
            21'b0001?_????_????_????_????: m<='d17;
            21'b00001_????_????_????_????: m<='d16;
            21'b00000_1???_????_????_????: m<='d15;
            21'b00000_01??_????_????_????: m<='d14;
            21'b00000_001?_????_????_????: m<='d13;
            21'b00000_0001_????_????_????: m<='d12;
            21'b00000_0000_1???_????_????: m<='d11;
            21'b00000_0000_01??_????_????: m<='d10;
            21'b00000_0000_001?_????_????: m<='d9;
            21'b00000_0000_0001_????_????: m<='d8;
            21'b00000_0000_0000_1???_????: m<='d7;
            21'b00000_0000_0000_01??_????: m<='d6;
            21'b00000_0000_0000_001?_????: m<='d5;
            21'b00000_0000_0000_0001_????: m<='d4;
            21'b00000_0000_0000_0000_1???: m<='d3;
            21'b00000_0000_0000_0000_01??: m<='d2;
            21'b00000_0000_0000_0000_001?: m<='d1;
            21'b00000_0000_0000_0000_0001: m<='d0;
            default: m <= 5'dx;
        endcase
       else
       m<='bz;
    end
end 
endmodule 

 

仿真

資源占用

可以看出采用casez的話效果更佳而且資源占用較少速度不會因為被測數據的大小發生變化。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM