Skip to content

Counting flipped bits with sum() with(), not $countones()

write-from-scratch / multi-constraint / cross-call-state / array

$countones() would make this trivial; the point is the array-reduction technique. sum() with needs an array, and current_data ^ previous_data is a single packed value. Two things that look like they should work and don’t compile: chaining the streaming operator {<<{...}} into a method call, and comparing an unpacked array to a streaming expression with ==.

What works: an array of rand bit, each element tied to one bit of the XOR by a foreach constraint, then reduced. Cast each element with int'(item), or the count wraps at 1 bit.

Fix the class below.

Requirements

  1. toggle_target is between 1 and 32, inclusive.
  2. changed_bits[k] == current_data[k] ^ previous_data[k] for every k, via foreach.
  3. changed_bits.sum() with (int’(item)) == toggle_target.
  4. post_randomize() sets previous_data to current_data, so the next randomize() measures its distance from this one. previous_data is static, so this holds across objects too.

Source on GitHub

n_bit_hamming_delta.sv