I am learning bit manipulation and have come across the following code. I’m trying to work out what it does:
long func_c(unsigned long x) {
long val = 0;
// sums of bits in x (done in parallel for each byte segment)
for (int i = 0; i < 8; i++) {
val += (x & 0x0101010101010101L);
x >>= 1;
}
// adds the top 32 bits to the lowest 32 but why?
val >>= (val >> 32);
// adds the top 16 bits to the lowest 16 but why?
val >>= (val >> 16);
// adds the top 8 bits to the lowest 8 but why?
val >>= (val >> 8);
// gets the lowest byte
return val & 0xff;
}
What are the series of right shifts trying to achieve?