C实现奇偶校验
奇偶校验原理(来自百度百科):奇偶校验(Parity Check)是一种校验代码传输正确性的方法。根据被传输的一组二进制代码的数位中“1”的个数是奇数或偶数来进行校验。采用奇数的称为奇校验,反之,称为偶校验。
C代码实现如下:
#include <stdio.h>
#define uint32_t unsigned int
#define uint16_t unsigned short
#define uint8_t unsigned char
/* 从data中获取第n bit的值 注:data只能为uint8*类型指针 */
#define GET_BIT_N_VAL(data, n) \
(0x1 & (( *((data) + (n)/8) & (0x1 << ((n)%8)) ) >> ((n)%8)))
uint8_t soc_gen_even_parity_common(uint8_t *entry_data, uint16_t entry_len)
{
uint32_t i = 0;
uint32_t even_parity = 0;
for(i = 0; i < entry_len; i++)
{
even_parity += GET_BIT_N_VAL((entry_data), i);
}
return (even_parity & 0x1);
}
uint8_t soc_gen_old_parity_common(uint8_t *entry_data, uint16_t entry_len)
{
uint32_t i = 0;
uint32_t odd_parity = 0;
for(i = 0; i < entry_len; i++)
{
odd_parity += odd_parity+ GET_BIT_N_VAL((entry_data), i);
}
if (odd_parity % 2 == 0)
return 1;
else
return 0;
}
int main(void)
{
uint8_t data[] = {0xff, 1, 0xff, 1};
uint8_t ret = 0;
uint8_t i = 0;
printf("original data: ");
for (i = 0; i < sizeof(data); i++)
printf("0x%x ", data[i]);
printf("\n");
ret = soc_gen_even_parity_common(data, sizeof(data) * 8);
printf("even parity result: %u\n", ret);
ret = soc_gen_old_parity_common(data, sizeof(data) * 8);
printf(" odd parity result: %u\n", ret);
return 0;
}
编译运行测试:
$ ./a.out
original data: 0xff 0x1 0xff 0x1
even parity result: 0
odd parity result: 1
分析运行结果,输入的原始数据为:0xff 0x1 0xff 0x1,则”1″的个数为8+1+8+1=18,采用偶校验,”1″的个数为偶数,所以结果为1;采用奇校验,“1”的个数为奇数,所以结果为1。