On Sat, Jun 13, 2020 at 07:10:50PM -0000, Christian Weisgerber wrote:
> On 2020-06-13, Theo Buehler <[email protected]> wrote:
>
> > Others have pointed out off-list that one can use __builtin_popcount(),
> > but __builtin_parity() is exactly what I want. Is it available on all
> > architectures?
>
> The standard implementation will be perfectly fine, no need to resort
> to magic compiler built-ins.
>
I was curious.
> int
> popcount(uint16_t x)
> {
> x = (x & 0x5555) + ((x & 0xAAAA) >> 1);
> x = (x & 0x3333) + ((x & 0xCCCC) >> 2);
> x = (x & 0x0F0F) + ((x & 0xF0F0) >> 4);
> x = (x & 0x00FF) + ((x & 0xFF00) >> 8);
> return (x);
> }
>
> ... which immediately lends itself to:
Yes. Thank you!
>
> int
> parity(uint16_t x)
> {
> x = (x & 0x5555) ^ ((x & 0xAAAA) >> 1);
> x = (x & 0x3333) ^ ((x & 0xCCCC) >> 2);
> x = (x & 0x0F0F) ^ ((x & 0xF0F0) >> 4);
> x = (x & 0x00FF) ^ ((x & 0xFF00) >> 8);
> return (x);
> }
>
> --
> Christian "naddy" Weisgerber [email protected]
>