C++程序可以有效地找到数字的奇偶校验

C++ program to find the Parity of a number efficiently

在本文中,我们将讨论一个程序来查找给定数字N的奇偶校验。

奇偶校验定义为数字的二进制表示形式中的设置位数(" 1"的数量)。

如果二进制表示形式中的" 1"数量为偶数,则将奇偶校验称为偶数奇偶校验;如果二进制表示形式中的" 1"的数量为奇数,则该奇偶校验称为奇数奇偶校验。

如果给定数字为N,我们可以执行以下操作。

  • y = N ^(N >> 1)
  • y = y ^(y >> 2)
  • y = y ^(y >> 4)
  • y = y ^(y >> 8)
  • y = y ^(y >> 16)

完成所有这些操作后,y中最右边的位将代表数字的奇偶校验。 如果该位为1,则奇偶校验为奇数;如果该位为0,则奇偶校验为偶数。

现场演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <bits/stdc++.h>
using namespace std;
bool calc_parity(int N) {
 int y;
 y= N ^ (N >> 1);
 y = y ^ (y >> 2);
 y = y ^ (y >> 4);
 y = y ^ (y >> 8);
 y = y ^ (y >> 16);
 //checking the rightmost bit
 if (y & 1)
   return 1;
 return 0;
}
int main() {
 int n=1345;
 int result = calc_parity(n);
 if(result==1)
   cout <<"Odd Parity" << endl;
 else
   cout <<"Even Parity" << endl;
 return 0;
}

输出量

1
Even Parity