Convert one hot bit vector to an integer in SystemVerilog without logarithms

1.8k Views Asked by At

I have a bit vector (one hot encoded, aka, one and only one bit will be 1) that represents a bitmap over another vector. For example, lets say these are my variables:

logic [3:0] bitmap;
logic [7:0] data_vector[3:0];
assign bitmap = 4'b0010;

I would like to access the index of data_vector that corresponds with the asserted bit in bitmap (data_vector[1] for this example). An obvious way would be the following:

logic [7:0] selection;
always_comb begin
   for (integer i = 0; i < 4; i++) begin 
      if (bitmap[i]) begin
         selection = data_vector[i];
      end
   end
end

I was wondering if there was a more efficient way to do this. The following is not a possibility

   selection = {8{bitmap[0]}} & data_vector[0] | ... 
              |{8{bitmap[3]}} & data_vector[3];

as this is just a small example to explain the question. Thanks in advance :)

1

There are 1 best solutions below

1
dave_59 On

You can do

selection = data_vector[$clog2(bitmap));

If this needs to be synthesizable AND your synthesis tool does not support $clog2, then you could write the function yourself, or stick with what you originally wrote.