C语言解决折叠加密问题

版权声明:所有分享的源代码仅供学习使用,欢迎分享转载,请注明出处 https://blog.csdn.net/weixin_43328024/article/details/84402745

C语言解决折叠加密问题

题目
给一个长度为 的字符数组和一个长度为k的01数组req,根据要求编写折叠加密和解密的算法。
折叠加密方法举例:
reg[i]=0,表示从左到右折叠
a b c d e f g h 折叠加密后 d c b a
e f g h
d c b a 折叠加密后 f e
e f g h c d
b a
g h
reg[i]=1,表示从右到左折叠
a b c d e f g h 折叠加密后 h g f e
a b c d
f e 折叠加密后 h
c d a
b a d
g h e
f
c
b
g

源代码分享如下:

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

int main()
{
	int a,n,b=1,c=2,m,p;
	char str[50];//存字符 
	char stn[50];//存K 
	
	printf("请输入秘钥:"); 
	scanf("%s",str);

	printf("请输入k:"); 
	scanf("%s",stn);
	
	n=strlen(str);//计算字符长度 
	p=n;
	m=strlen(stn);//计算K的长度 
	
	char k[n][n];//n维数组 用来存结果 
	
	for(a=0;a<n;a++)
	 for(int l=0;l<n;l++)
	  k[a][l]=0;
	
	for(a=0;a<n;a++)
	k[n-1][a]=str[a];
	for(int j=0;j<m;j++)
	{
		int d=0;
		if(stn[j]=='1') //为1 的时候 
		{
			for(int l=0;l<b;l++)
			{
				for(int i=p/2;i<p;i++)
				{
					k[n-c+d][p-i-1]=k[n-1-d][i];
					k[n-1-d][i]=0;
				}
				d++;							
			}
		}
		else // 为0 的时候 
		{
			for(int l=0;l<b;l++)
			{
				for(int i=0;i<p/2;i++)
				{
					k[n-c+d][p/2-i-1]=k[n-1-d][i];
					k[n-1-d][i]=k[n-1-d][p/2+i];
					k[n-1-d][p/2+i]=0;
				}
				d++;
			}
		}
		p=p/2;
		b*=2;
		c*=2;
		printf("第%d次加密后为:\n", j+1);
		for(int i=n-b;i<n;i++)
			{
			printf("\t\t%s",k[i]);
			printf("\n");
			}	
	}
	return 0;
 } 

运行结果(以abcdefgh为例):
在这里插入图片描述
以上就是关于折叠加密问题的源代码分享,希望业界大佬多多指教,也希望小白能够从中受益!

猜你喜欢

转载自blog.csdn.net/weixin_43328024/article/details/84402745
今日推荐