user2683458
user2683458

Reputation: 105

verilog generate for if/else

I trying to write some code like (in verilog):

parameter N = 128;

   if (encoder_in[0] == 1) begin
 23     binary_out = 1; 
 24    end else if (encoder_in[1] == 1) begin
 25     binary_out = 2; 
 26    end else if (encoder_in[2] == 1) begin
 27     binary_out = 3; 
 28    end else if (encoder_in[3] == 1) begin
 29     binary_out = 4; 
 30    end else if (encoder_in[4] == 1) begin
 31     binary_out = 5; 
 32    end else if (encoder_in[5] == 1) begin
 33     binary_out = 6; 
 34    end else if (encoder_in[6] == 1) begin
 35     binary_out = 7; 
 36    end else if (encoder_in[7] == 1) begin
 37     binary_out = 8; 
......
......
 36    end else if (encoder_in[127] == 1) begin
 37     binary_out = 8; 
       end

I want that I can change N to any value I want and it still works. "generate for" will works here? like that:

parameter N = 128;

if (encoder_in[0] == 1) begin
binary_out = 1; 
generate for (i=1; i<N; i=i+1) begin
   end else if (encoder_in[i] == 1) begin
   binary_out = i+1; 
end endgenarate

end

if not, what can I do? Thanks a lot!

Upvotes: 2

Views: 4806

Answers (1)

Greg
Greg

Reputation: 19096

A generate block cannot be used inside a another statement. I'm still looking for the exact reference in the IEEE std 1800-2012.

If you want an decoder with higher priority to the LSB, then the following will work without an using a generate block:

parameter N = 128;
integer i;
...
always @* begin
    binary_out = 0; // default value
    ...
    for(i=N-1; i>=0; i=i-1) begin
        if (encoder_in[i]==1'b1) begin
            binary_out = i+1;
        end
    end
end

Note that this is using a count down for loop. A count up would give priority to the MSB.

Upvotes: 5

Related Questions