Q:

Population count between two positions

I am looking for a solution of finding pop count in bitstring between two positions
eg:
popcnt( 10(0101), 0, 3) = 1
popcnt( 100101(), 0, 0) = 0
popcnt( 10010(1), 0, 1) = 0

** I am assuming open range and assuming Right to Left order
using standard bit operators and possibly popcnt or equivalent.
If it makes difference, I am looking to find the popcnt between the difference of two strings.  Lets say i have string b and i swap bits in two positions, eg 0101110 -> 1101100 => 3 - I need the popcnt between the bits that changed - in the case of 0101110 -> 1101100 the bits between the two are 10110 and so popcnt is 3
Do you see some ingenious way to do so with bithacks?

A:

First mask the value to get only the relevant bits:
relevant = (value >> startBit) & ((1 << numOfBits) - 1);

Edit:
The above will invoke undefined behavior when numOfBits == 32 (or more accurately, when numOfBits == CHAR_BIT * sizeof(int)). To fix this you need to have special handling for that case (set relevant = value).

Then find the population count of those bits using one of the methods proposed in this question: Best algorithm to count the number of set bits in a 32-bit integer. 
To summarize the answers, You can use a platform-specific function such as GCC's __builtin_popcount, or if you need a portable solution you can use a parallel-prefix algorithm such as the one from Matt Howells's answer:
int NumberOfSetBits(int i)
{
    i = i - ((i >> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
    return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}

