wie kann ich die Anzahl der gesetzten Bits in einem uint in Specman zählen?

StackOverflow https://stackoverflow.com/questions/435188

  •  10-07-2019
  •  | 
  •  

Frage

Ich möchte die Anzahl der gesetzten Bits in einem uint in Specman zählen:

var x: uint;
gen x;
var x_set_bits: uint;
x_set_bits = ?;

Was ist der beste Weg, dies zu tun?

War es hilfreich?

Lösung

I don't know Specman, but another way I've seen this done looks a bit cheesy, but tends to be efficient: Keep a 256-element array; each element of the array consists of the number of bits corresponding to that value. For example (pseudocode):

bit_count = [0, 1, 1, 2, 1, ...]

Thus, bit_count2 == 1, because the value 2, in binary, has a single "1" bit. Simiarly, bit_count[255] == 8.

Then, break the uint into bytes, use the byte values to index into the bit_count array, and add the results. Pseudocode:

total = 0
for byte in list_of_bytes
    total = total + bit_count[byte]

EDIT

This issue shows up in the book Beautiful Code, in the chapter by Henry S. Warren. Also, Matt Howells shows a C-language implementation that efficiently calculates a bit count. See this answer.

Andere Tipps

One way I've seen is:

x_set_bits = pack(NULL, x).count(it == 1);

pack(NULL, x) converts x to a list of bits.
count acts on the list and counts all the elements for which the condition holds. In this case the condition is that the element equals 1, which comes out to the number of set bits.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top