奇偶检验码(C语言实现)

 计算机组成原理作业:

        用c语言实现奇偶校验

奇校验:

        大概意思就是二进制数最右边加一个数字(0或1)使得1出现的次数为奇数

偶校验类似

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
	@author sjn
	@date 2022-2-27
*/

//取得对应的二进制数中1出现的次数
int getOccurrenceTimes(int num) {
	int count = 0;
	while(num){  
		num = num & (num - 1);  
		count++;  
	}
	return count;
}

//奇校验: 当 1 出现的次数为奇数时候在最后面加上 0,否则加 1 
//str为传入的字符串,times是1出现的次数
void oddCheck(char *str, int times) {
	times & 1 ? strcat(str, "0") : strcat(str, "1");
} 

//偶校验:与奇校验相反 
//参数同奇校验 
void evenCheck(char *str, int times) {
	times & 1 ? strcat(str, "1") : strcat(str, "0");
}

int main() {
	int num;
	scanf("%d",&num);
	//取得num对应的二进制中1出现的次数 
	int times = getOccurrenceTimes(num);
	char str[99];//存储字符串
	//itoa函数
	//num->要转换的数字,str->要写入转换结果的目标字符串,2->转移数字时所用的基数
	//itoa(num,str,2)就是把num转换成二进制形式的字符串并存储在str字符数组中 
	itoa(num,str,2);
	printf("1 occurrences Times : %d\n",times);
	printf("The original str : %s\n",str);
	//奇校验 
	oddCheck(str, times);
	printf("After odd check str : %s",str);
	
	return 0;
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值