2

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!

0

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1. you can use conditional generate statements without an always block, but the condition should be a constant, such as a parameter. In this case, encoder_in cannot be used since it is an input, and your solution is correct.
@user2683458, if this answer was useful, then please click accept. If not, what additional information is needed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.