in reply to Efficient bit counting with a twist.
Build a bit mask for the byte that contains the position. Then count the bits in the bytes before the position, and do a bitwise and for the byte that contains the position.
my $mask = pack "V", 2 ** ($p % 8) - 1; my $c = unpack( '%32b*', substr( $v, 0, $p / 8 ) ) + unpack( '%32b*', substr( $v, $p / 8, 1 ) & $mask );
(Update: removed a superfluous pair of parens in the last line.)
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Efficient bit counting with a twist.
by BrowserUk (Patriarch) on Jan 27, 2013 at 08:33 UTC | |
by quester (Vicar) on Jan 27, 2013 at 09:02 UTC |
In Section
Seekers of Perl Wisdom