http://qs321.pair.com?node_id=1015566


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.)