A priority encoder is a combinational circuit that, when given an input bit vector, outputs the position of the first 1 bit in the vector. For example, a 8-bit priority encoder given the input 8'b10010000 would output 3'd4, because bit[4] is first bit that is high.
Build a 4-bit priority encoder. For this problem, if none of the input bits are high (i.e., input is zero), output zero. Note that a 4-bit number has 16 possible combinations.
个人答案:(验证正确)
module top_module (
input [3:0] in,
output reg [1:0] pos );
always@(*) begin
if(in == 4'b0)
pos = 2'b0;
else if(in == 4'b1000)
pos = 2'd3;
else if((in == 4'b100)||(in == 4'b1100))
pos = 2'd2;
else if (in == 4'b10 || in == 4'b110 || in == 4'b1010 || in == 4'b1110)
pos = 2'd1;
else
pos = 2'd0;
end
endmodule
更优解:
always @(*) begin
casez (in[3:0])
4'bzzz1: out = 0; // in[3:1] can be anything
4'bzz1z: out = 1;
4'bz1zz: out = 2;
4'b1zzz: out = 3;
default: out = 0;
endcase
end
此题可以延申到:用组合逻辑进行序列检查(待思考)