数字奇偶校验
奇偶校验基于数字的二进制等效数中的数字“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