C语言编程题目(5)单字符的位处理 数据加密

题目如下:

  这道题目理解起来其实并不难,关键是加密算法的实现,这里先把关键函数贴上来:

代码1

 1 char CharConv(char Mark)
 2 {
 3     int orgin_num = Mark;     // get ascii value of char
 4     int i = 0,temp = 0;
 5     int Arr[8],LeftArray[5];
 6     for(i=0;i<8;i++)
 7         Arr[i] = (Mark>>i)&1;   //save binary bit(8 bits per char) into array
 8     i = Arr[0];             //switch bit(0 <--> 1 2 <--> 3 4 <--> 5)
 9     Arr[0] = Arr[1];
10     Arr[1] = i;
11     i = Arr[2];
12     Arr[2] = Arr[3];
13     Arr[3] = i;
14     i = Arr[4];
15     Arr[4] = Arr[5];
16     Arr[5] = i;
17     temp = Arr[6] + 2*Arr[7];   //bits of circle left shift
18     for(i=0;i<=5;i++)   
19         LeftArray[(i+temp)%6] = Arr[i]; //  here try to save new bit order into new temporary array
20     for(i=0;i<=5;i++)
21         Arr[i] = LeftArray[i];   
22     temp = 0;
23     for(i=0;i<8;i++)             //calculate new char's ascii
24         if(Arr[i] == 1)
25             temp += my2pow(i);
26     return (char)temp;           // return new char
27 }

 

  值得注意的是调用了自定义函数my2pow,返回2的x幂次值,之所以不用系统的pow函数是为了避免类型转换的麻烦(参数、返回值都是double类型):

1 int my2pow(int x){
2     int i = 0,result = 1;
3     while(i<x){
4         result *= 2;
5         i++;
6     }
7     return result;
8 }

  得到单个字符的加密转换以后,可以新建字符串加密函数StrConv,循环调用上面的CharConv函数返回加密的完整字符串。

代码2

1 void StrConv(char *src,char *dst,int length){
2     int index = 0;
3     while(index < length){
4         dst[index] = CharConv((char)src[index]);
5         index++;
6     }
7 }

  函数接受三个参数,第一个参数是源字符串,第三个参数是源字符串的长度;第二个参数是存储加密后字符串的地址。函数结构也十分清晰、简单。出过一些错,不能用dst+index这种方法,会有问题,dst是char *类型,dst+1也就是:(dst指向的地址+1个字节)地址。

代码3

 1 int main()
 2 {
 3     int N,index;
 4     char temp[21]={0};
 5     char *str_array[5][21]; // assume the value of N doesn't bigger than 5
 6     scanf("%d",&N);
 7 
 8     for(index=0;index<N;index++)
 9     {
10         scanf("%s",temp);
11         StrConv(temp,(char *)str_array[index],strlen(temp));
12         memset(temp,0,sizeof(temp));
13     }
14     for(index=0;index<N;index++)
15         printf("%s\n",str_array[index]);
16     return 0;
17 }

  最后是main函数,根据题目要求来依次输入N组字符串,每组字符串长度不超过20字节。然后每输入一组给temp临时字符数组,马上加密、依次保存到str_array指针数组,最后循环输出str_array数组的N组解密值。代码第11行容易出错,传参的类型不一致可能存在潜在风险。

执行结果:

    

posted @ 2019-08-29 11:29  爱吃砂糖橘的白龙  阅读(652)  评论(0编辑  收藏  举报