I want to use parity check function in a loop to make an event that happens every second times. But all the functions I found to watch parity don't work.
Even the most simple ones, like this:
unsigned int v;
bool parity = false;
while (v)
{
parity = !parity;
v = v & (v - 1);
}
Can give me the same value for an even number and for an odd number.
How to do it well? Or maybe, are there any other ways to to make an event that happens in every second round through the loop?
It seems like you're misunderstanding the meaning of "parity" as it's normally used in the world of computers. The code you've shown sets parity
to false
if the binary representation of v
has an even number of set bits, and to true
if it has an odd number of set bits. The concept of parity has nothing to do with v
being even or odd itself. Some examples:
Number (base 10) Number (base 2) Parity
0 0 0
1 1 1
2 10 1
3 11 0
4 100 1
5 101 0
6 110 0
7 111 1
. . .
. . .
. . .
12498741 1101 1110 1101 0111 0011 0101 0
. . .
. . .
. . .
If you really do want to check if a number is even or odd, you can use:
bool odd = v & 1;
bool even = !(v & 1);
Which are equivalent to the %
expression used in @user1118321's answer.