iam trying to get the number of the effective bits in an array for example: if i have an array that contains these sequence of bits: 0000_0101 the dimension of the array is 8 , i just want way to get the number of the most significant bits which are 3 in this case
Asked
Active
Viewed 983 times
2 Answers
1
Here is a function that behaves as described in the post:
module tb ();
reg [7:0] temp;
reg [7:0] myvector;
function automatic int returns_location(input reg [7:0] vector);
integer val = 0;
for(int i =0;i < $size(vector);i++)
if(vector[i]== 1'b1)
val = i;
return (val + 1);
endfunction
initial
begin
// From the post
temp = 8'b0000_0101;
$display("---- location of most sig 1 = %0d ----",returns_location(temp));
#1;
// Another example, shift 1 left
temp = 8'b0000_1101;
$display("---- location of most sig 1 = %0d ----",returns_location(temp));
#1
// Another example, shift 2 left
temp = 8'b0001_1101;
$display("---- location of most sig 1 = %0d ----",returns_location(temp));
#1
$finish;
end
endmodule
And produces the results:
# ---- location of most sig 1 = 3 ----
# ---- location of most sig 1 = 4 ----
# ---- location of most sig 1 = 5 ----

Mikef
- 1,572
- 2
- 10
- 21
0
Well, you're looking for number of bits enough to index into an 8b vector.
Assuming your variable (reg, logic) is named arr[] You could use: $clog2($bits(arr))
Here $bits(arr) would be 8. Then clog2(8) will be 3. This takes care of non-power of 2 widths also.
Edit: changed from clogb2() to clog2().
-
your answer would be valid only in this specific example but it couldn't be used as a general solution – Samuel Mikhael May 30 '22 at 11:38
-
there is no `$clogb2`, I think you meant `$clog2` – Greg May 30 '22 at 20:49
-
@Greg you're right. – Prathamesh Shinde May 31 '22 at 14:12
-
@SamuelMikhael: can you please elaborate? I believe it would work for any variable. – Prathamesh Shinde May 31 '22 at 14:13
-
1The post is asking for the bit index (1-based) of the most significant bit within a defined vector size. For example given an 8 bit vector and the number 0000_0001, 1 is the answer. Given 8 bit vector and 0000_0011, 2 is the answer, given 0000_0111 3 is the answer, given 0001_1010 5 is the answer, given 0010_
6 is the answer, given 0100_anything_7 is the answer, and given 1000_0000, 8 is the answer. The post asks for a Verilog built-in; there is none, however we cane write a function that does this. This could be considered of the number of used bits or most significant bits. – Mikef May 31 '22 at 15:45