3.1.1 Popcount function

EasyImplementVerilator · local serverReview the topic

Write a function that counts the 1 bits in a byte, wide enough to count all eight.

Hardware context: Reusable transaction construction and bus-driving routines. Count asserted bits in a known byte-wide hardware status or enable mask.

A byte-enable checker needs to know how many lanes of a write are active. That is a calculation with no waiting in it, so it belongs in a function: it runs in zero time and hands back a value.

Write popcount8(value), which returns how many of the 8 bits of value are 1. For 8'h81, bits 7 and 0 are set, so the answer is 2.

The answer can be anything from 0 to 8. A counter only 3 bits wide counts 0 to 7 and turns the all-ones byte into 0, so make sure the count has room for 8.

Signals in the timeline

SignalWidthRole
value8input of each check
Full specification
Signature (keep it)
function automatic int popcount8(input logic [7:0] value);

value is a known 8-bit value. Count every bit that is 1, from bit 0 to bit 7. Do not change anything outside the function.

Examples

Example 1

The two end bits
Input
value = 8'h81
Output
ones = 2

Bits 7 and 0 are set.

Example 2

No lane active
Input
value = 8'h00
Output
ones = 0

No bit is set.

Example 3

Every lane active
Input
value = 8'hFF
Output
ones = 8

All eight bits are set, and the count must not wrap to 0.

Constraints and contract

  • value is known; the result is 0 to 8.
  • The function takes no time and has no side effects.
  • Keep the signature.

Hints

Hint 1

Look at the bits one at a time. How many bits are there, and does your loop visit every one, including bit 7?

Hint 2

The count must be able to hold 8. What is the largest value a 3-bit variable can hold?

Hint 3

Start a counter at 0 on every call and add 1 for each bit that is set; return the counter.

What this judge verifies: Your function is called on all 256 byte values. Passing shows the count is right for every one.

259 checks on Verilator · local server. Run the examples first, then check the full regression. The suite is local and inspectable. A passing result establishes the tested cases, not a proof for all possible inputs.

See all 5 steps and the final capstone
Your code SystemVerilogSaved locally
Ln 1, Col 1Tab indents · Ctrl/⌘ + Enter runs samples
Not run yet

The two end bits

Input
value = 8'h81
Expected output
ones = 2

Bits 7 and 0 are set.

Run samples executes all 3 example checks. Check all tests runs 259 checks.

Verilator · local server