bitwise operators

What does this code do and how?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  unsigned func(unsigned num)

{
num=num^(num>>16);

num=num^(num>>8);

num=num^(num>>4);

num=num^(num>>2);

num=num^(num>>1);

return(num&1);

}
Looks like the bit parity calculation. The bit hacks page has a very similar example, only it uses a small table for the last two shift-xors: http://graphics.stanford.edu/~seander/bithacks.html#ParityParallel

(as for how, it assumes that unsigned is 32 bit, and xors all of its bits together - first 16 and the second 16, then first 8 of the result with the last 8, then first 4 of that result with the last 4, then first 2 with the last 2, then the first bit with the last bit. At that moment, the last bit holds the result of all those xors, and the rest of the bits has garbage, so it ands out that last bit and returns it)
Last edited on
Topic archived. No new replies allowed.