I am looking for a bit manipulation function that takes two bit strings and filters and compacts the first string based on the second, so only the values where the second string are 1 are kept. Eg:
01101010 and 11110000 gives 00000110
01101010 and 00001111 gives 00001010
01101010 and 10101000 gives 00000011
By using looping, conditionals and working with each bit independently this is easy to implement, but I'm looking for a faster method using bit manipulation tricks if one exists, not using conditionals and loops. It does not have to work for input longer than 32 bits. Therefore a solution would have a signature like: uint32_t filter(uint32_t in, uint32_t mask)
In C it would look something like this with arrays and a loop:
void filter(bool in[], bool mask[], bool out[], int size) {
int output_index = 0;
for (int input_index = 0; input_index < size; ++input_index) {
if (mask[input_index]) {
out[output_index++] = in[input_index];
}
}
}
Here are a bunch examples of the types of solutions I'm looking for: Bit Twiddling Hacks