topic description
Implement a module that can count the number of 1s in the input data, for example, input data=8'b1011_0110, then output number=5. But consider the optimal way of writing resources.
problem solving ideas
A divide-and-conquer idea is used, and the addition operation is replaced by a bitwise operation, which uses fewer resources than directly adding the 8-bit data of the input data one by one.
The realization principle is to use multiple bitwise AND operations to realize addition.
The first bitwise AND realizes that the addition of 0 and 1 bits of data is stored in the [0:1] bit of data1, the addition of 2 and 3 bits of data is stored in the [2:3] bit of data1, the addition of 4 and 5 bits of data is stored in the [4:5] bit of data1, and the addition of 6 and 7 bits of data is stored in the [6:7] bit of data1.
The second bitwise AND realizes data1[0:1]bit + data1[2:3]bit; stored in [3:0]bit of data2, data1[4:5]bit + data1[6:7]bit; stored in [7:4]bit of data2.
The third bitwise AND realizes [3:0]+data2[7:4] of data2.
the code
module find_num_1(
input [7:0]data,
output [7:0]number
);
parameter m1 = 8'b01010101;
parameter m2 = 8'b00110011;
parameter m3 = 8'b00001111;
wire [7:0]data1;
wire [7:0]data2;
assign data1 = (data & m1) + ({data[0],data[7:1]} & m1);
assign data2 = (data1 & m2) + ({data1[1:0],data1[7:2]} & m2);
assign number = (data2 & m3) + ({data2[3:0],data2[7:4]} & m3);
endmodule
testbench
initial begin
data = 8'b1111_1111;
#10
data = 8'b1101_1010;
#50
$finish();
end
initial begin
$fsdbDumpfile("find_number_1.fsdb");
$fsdbDumpvars(0);
end
endmodule