数字的奇偶校验是基于该数字的二进制等效项中存在的1的数字。当当前1的计数为奇数时,它返回奇校验,对于偶数的1,它返回偶校验。
我们知道计算机内存中的数字以二进制数字存储,因此我们可以轻松地对数字进行移位。在这种情况下,通过移位这些位,我们将以给定数字的二进制等效值计算存在的1的数目。
Input: A number: 5 Binary equivalent is (101) Output: Parity of 5 is Odd.
finParity(n)
输入:数字n。
输出:检查数字具有偶校验还是奇校验。
Begin count := 0 temp := n while temp >= 2, do if temp has 1 as LSb, then count := count + 1 temp := right shift temp for 1 bit done if count is odd number, then display it is odd parity else display even parity End
#include <iostream> using namespace std; bool findParity(int n) { int count = 0; int temp = n; while (temp>=2) { if(temp & 1) //when LSb is 1, increase count count++; temp = temp >> 1; //right shift number by 1 bit } return (count % 2)?true:false; } int main() { int n; cout << "Enter a number: "; cin >>n; cout << "Parity of " << n << " is " << (findParity(n)?"Odd":"Even"); }
输出结果
Enter a number: 5 Parity of 5 is Odd