在通讯传输数据过程中,往往要加校验码,今天写了个简单的异或以及解异或的操作代码:
#include <stdio.h>
//这是加密(异或)过程
int Xor_fun(unsigned int *dat, int size)
{
int i;
for(i=0;i<size;i++)
{
dat[i+1] = dat[i+1] ^ dat[i];
}
return *dat;
}
//这是解密(解异或)过程
int Dxor_fun(unsigned int *dat, int size)
{
int i;
for(i=size-1;i>=0;i--)
{
dat[i] = dat[i-1] ^ dat[i];
}
return *dat;
}
int main () {
int i;
printf("The function is running\n");
unsigned int buf[29]={0x05,0x08,0x01,0x91,0x2c,
0x00,0x02,0xd1,0x2c,
0x00,0x03,0x2c,0xfa,
0x00,0x04,0xb0,0xc8,
0x00,0x06,0x40,0x96,
0xc8,0xdc,0x21,0x3c,
0xc9,0x40,0x21,0x28};
Xor_fun(buf,29);
printf("the result of xor:\n");
for(i=0;i<29;i++)
{
printf("buf[%d] = %#X\n",i,buf[i]);
}
Dxor_fun(buf,29);
printf("the result of drox:\n");
for(i=0;i<29;i++)
{
printf("buf[%d] = %#X\n",i,buf[i]);
}
return 0;
}