One Hot Check

in #blog7 years ago

We would like to know is only one bit in a vector is set.
There are many ways to implement this. Here is one efficient way.
We would build a tree of ORs and ANDs. The output valid bit would be set if all ANDs are 0 and at least one bit is 1.

module one_hot_check
#parameter VEC_WIDTH=8
(
input wire [VEC_WIDTH-1:0] vec_in,
output wire valid_one_hot
);

reg [VEC_WIDTH-1:1] and_array ;
reg [2*VEC_WIDTH-1:1] or_array ;
integer i ;

always @(vec_in)
begin
and_array = {(VEC_WIDTH-1){1'b0}} ;
or_array = {vec_in,{(VEC_WIDTH-1){1'b0}}} ;

for (i=2*VEC_WIDTH-1; i >2; i=i-2)                  
  begin                                             
    or_array [i/2] = or_array[i] | or_array[i-1] ;  
    and_array[i/2] = or_array[i] & or_array[i-1] ;  
  end // for loop                                   

end // always

assign valid_one_hot = (~(|and_array) & or_array[1]);
endmodule