#include <stdio.h>
#include <stdint.h>
uint32_t extract_even_bits(uint32_t reg) {
uint32_t index = 0;
uint32_t val = 0;
while (reg)
{
val |= ((reg&1U)<<index);
index++;
reg = reg>>2;
}
return val;
}
int main() {
uint32_t reg;
scanf("%u", ®);
printf("%u", extract_even_bits(reg));
return 0;
}
Solving Approach
I check the value of the first bit and add it to the val variable in its corresponding position index. The I right shift the reg by 2 to get the next even-positioned bit.
When there is no more 'ones' in reg, the while loop exits and returns val.