Search This Blog

Friday 18 August 2023

Verilog code to count number of 1's and 0's in 32-bit data input

There are many places where we need to check how many 0's or 1's are present in incoming data. It can be packet inspection or these counting further can be used for different purposes. This Verilog code is designed to efficiently count the occurrences of both '1' and '0' bits within a 32-bit input data. The primary objective of this module is to provide an accurate count of the number of '1's and '0's present in the input data simultaneously. Module takes 32-bit input data with valid bit. There are also clock and reset signals. Module has two output count vlaues, one for number of 1's and another one for number of 0's, and one valid signal. 32-bit input data is fed to the function only on valid_input and function will return number of 1's in the 32-bit data. This value will be subtracted from 32 and it will give us number of 0's present in the data. Both output values are true only when output_valid signal is high.

module count_ones_zeros(
    input clk,
    input reset,
    input valid_input,
    input [31:0] data,
    output reg [5:0] num_ones,
    output reg [5:0] num_zeros,
    output reg output_valid
);

    reg [31:0] stored_data;
    reg valid_output;

    function automatic int_count_ones_zeros;
        input [31:0] input_data;
        int_count_ones_zeros = 0;
        for (integer i = 0; i < 32; i = i + 1) begin
            if (input_data[i] == 1'b1)
                int_count_ones_zeros = int_count_ones_zeros + 1;
        end
    endfunction

    always @(posedge clk) begin
        if (reset) begin
            stored_data <= 32'b0;
            valid_output <= 1'b0;
        end else if (valid_input) begin
            stored_data <= data;
            valid_output <= 1'b1;
        end else begin
            valid_output <= 1'b0;
        end

        num_ones <= int_count_ones_zeros(stored_data);
        num_zeros <= 32 - num_ones;
        output_valid <= valid_output;
    end

endmodule

No comments:

Post a Comment