数字的奇偶校验


数字的奇偶性基于该数字的二进制等价数中存在的 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

更新于: 17-Jun-2020

6 千+

职业生涯更上一层楼

完成课程获得认证

开始
广告
© . All rights reserved.