數字奇偶校驗
奇偶校驗基於數字的二進位制等效數中的數字“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
廣告
資料結構
網路技術
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP