March 11, 2024

I had a brain hiccup with __builtin_parity


Tags:  #Etcetera


<et cetera>

Two things:

  1. I work with bits often on a daily basis.
  2. I’m pretty stupid and my brain occasionally has a hiccup… like it did today.

While looking through one of gcc’s built-in functions, __builtin_parity:

Built-in Function: int __builtin_parity (unsigned int x)
    Returns the parity of x, i.e. the number of 1-bits in x modulo 2. 

For a brief moment, I forgot what parity meant and just took the documentation for its word: the number of 1-bits in x modulo 2. The problem, however, was that I didn’t use my brain. I thought it was “the number of 1-bits in (x modulo 2)” instead of “(the number of 1-bits in x) modulo 2”.

The former is just (x modulo 2).

Examples:

124 (base 10): 00000000 01111100
Parity: 1 -> there are five 1s; 5 % 2 = 1
Instead of 124 % 2 = 0

423 (base 10): 00000001 10100111
Parity: 0 -> there are six 1s; 6 % 2 = 0
Instead of 423 % 2 = 1

</et cetera>