http://www.perlmonks.org?node_id=1015564
BrowserUk has asked for the wisdom of the Perl Monks concerning the following question:

Given a bit vector $v, this: my $c = unpack '%32b*', $v; will count the set bits very efficiently.

However, I need to count the set bits preceding (not including) a given bit position within $v.

I can do that using:

## $p = position my $c = 0; vec( $v, $_, 1 ) and ++$c for 0 .. $p - 1;

But that is grossly inefficient for large vectors.

Can you do it more efficiently?

Note:The rest of the code is pure perl, so I'd rather avoid going to XS to do this if possible.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.