LFSR

c语言中实现LFSR;

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
#define DIGIT 34
void conversion(unsigned long long num,int* arr) {
	for (int i = 0; i < DIGIT; ++i) {
		arr[DIGIT - 1 - i] = num%2;
		num /= 2;
	}
}
void lfsr(int* arr1,int* arr2,int* target) {
	int x;
	for (int i = 0; i < DIGIT; ++i) {
		target[i] = arr1[3];
		x = ((arr1[0] * arr2[0] + arr1[1] 
			* arr2[1] + arr1[2] * arr2[2]
			+ arr1[3] * arr2[3]) % 2);
		int y = DIGIT-1;
		for (; y > 0;--y) {
			arr1[y] = arr1[y - 1];
		}
		arr1[0] = x;
	}
}
void J_K(int* J, int* K, int* key) {
	if ((J[0] == 0 && K[0] == 0) || (J[0] == 1 && K[0] == 1)) {
		key[0] = J[0];
	}
	else if (J[0] == 1 && K[0] == 0) {
		key[0] = 1;
	}
	else {
		key[0] = 0;
	}
	for (int i = 1; i < DIGIT; ++i) {
		if (J[i] == 0 && K[i] == 0) {
			key[i] = key[i - 1];
		}
		else if (J[i] == 0 && K[i] == 1) {
			key[i] = 0;
		}
		else if (J[i] == 1 && K[i] == 0) {
			key[i] = 1;
		}
		else {
			key[i] = key[i - 1] ^ 1;
		}
	}
}
void ead(int* arr1, int* arr2, int* arr3) {
	for (int i = 0; i < DIGIT; ++i) {
		arr3[i] = arr1[i] ^ arr2[i];
	}
}

void B_D(int* arr) {
	unsigned long long result = 0;
	for (int i = 0; i < DIGIT; ++i) {
		result += arr[i] * pow(2, DIGIT - 1 - i);
	}
	printf(" 学号:");
	printf("%llu\n", result);
}
int main() {
	unsigned long long snum = 16100101116;
	int arr[1024] = { 0 };
	conversion(snum, arr);
	printf(" 原码:");
	for (int i = 0; i < DIGIT; ++i) {
		printf("%d", arr[i]);
	}
	printf("\n");
	int J[DIGIT] = { 0 };
	int K[DIGIT] = { 0 };
	int key[DIGIT] = { 0 };
	int cry[DIGIT] = { 0 };
	int arr0[1024] = { 1,0,1,0 };
	int arr1[1024] = { 0,1,0,1 };
	int arr2[1024] = { 1,1,0,0 };
	lfsr(arr0, arr1, J);
	lfsr(arr0, arr2, K);
	J_K(J, K, key);
	printf("J序列:");
	for (int i = 0; i < DIGIT; ++i) {
		printf("%d", J[i]);
	}
	printf("\n");
	printf("K序列:");
	for (int i = 0; i < DIGIT; ++i) {
		printf("%d", K[i]);
	}
	printf("\n");
	printf(" 密钥:");
	for (int i = 0; i < DIGIT; ++i) {
		printf("%d", key[i]);
	}
	printf("\n");
	ead(arr, key, cry);
	printf(" 密文:");
	for (int i = 0; i < DIGIT; ++i) {
		printf("%d", cry[i]);
	}
	printf("\n");
	ead(key, cry, cry);
	printf(" 原码:");
	for (int i = 0; i < DIGIT; ++i) {
		printf("%d", cry[i]);
	}
	printf("\n");
	B_D(cry);
	system("pause");
	return 0;
}

你可能感兴趣的:(成长之路)