Search code examples
verilogsystem-verilog

Check all bits set/unset


I'm new to Verilog, and I'm taking my first steps with FPGA "programming". I have a parametrized module definition similar to that:

module foobar #(
    parameter BITS = 4
) (...);

   reg[BITS - 1:0] counter = 0;
   ...
   if (counter == |) begin
      ...
   end
   ...
endmodule

and want to test at | whether all bits of counter are set (or unset). How to achieve that? Without parametrization, it would be easy by specifying, e.g. 4'b1111 (or 4'b0000).


Solution

  • Use the replicated concatenation operator. Check if all bits set:

       if (counter == {BITS{1'b1}}) begin
    

    Check if all bits cleared:

       if (counter == {BITS{1'b0}}) begin
    

    Alternately, with SystemVerilog features enabled:

       if (counter == '1) begin // All set
       if (counter == '0) begin // All cleared