The second question about "tells the position of first 1" (priority encoder) is still pending. There are basically two methods
- based on the output of the leading bit detector, which is already "one hot" encoded.
- based on the input directly
The first solution ends up in a wide or expression for each position bit and one additional for the all zero case, like below:
Code:
FOR J IN 0 TO NBITA-1 LOOP
FOR I IN 0 TO NBIT-1 LOOP
tmp_mask(I) := to_unsigned(i,NBITA)(J);
END LOOP;
q(J) <= OR_REDUCE(tmp_mask AND dataout);
END LOOP;
zero <= NOT OR_REDUCE(dataout);
A consideration about priority encoder designs can be found in the Arbitration chapter of the Altera Advanced Synthesis Cookbook. It also mentions a priority masking method using an adder similar to Permute's suggestion.
https://www.altera.com/literature/manual/stx_cookbook.pdf