in reply to Incrementing only the masked bits

I don't know of an immediate way to do this.

If you have k bits sets in your mask, the whole iteration has 2**k values. So what you're looking for is a function n_to_masked($mask, $n) that maps a number from 0 .. 2**k-1 to a 32-bit value that fits in your mask. I don't have a really clever way of doing this other than shifting bits left and right, but with $m you know exactly what bits you need to shift how much.

Update: tye's way is muuuuch more clever. Use that. :-)