數字的奇偶校驗


數字的奇偶性基於該數字的二進位制等價數中存在的 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.