Created
October 22, 2015 21:56
-
-
Save yudi-matsuzake/bcc04c3a9e8d77d5e37c to your computer and use it in GitHub Desktop.
cifra afim
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#define USAGE "USAGE: %s <cifra|decifra> [arquivo_entrada.txt]\n" | |
#define BUFFER_SIZE 2048 | |
#define CMD_CIFRA "cifra" | |
#define CMD_DECIFRA "decifra" | |
#define N_ALF 26 | |
#define A 7 | |
#define B 22 | |
void troca(int*a, int*b){ | |
int cup = *a; | |
*a = *b; | |
*b = cup; | |
} | |
int inversa_modular(int a, int b){ | |
int x[2] = {1, 0}; | |
int y[2] = {0, 1}; | |
int temp[2]; | |
if(b > a) | |
troca(&a, &b); | |
while(b != 0){ | |
int antb = b; | |
int q = a/b; | |
b = a%b; | |
a = antb; | |
temp[0] = x[0] - x[1]*q; | |
temp[1] = y[0] - y[1]*q; | |
x[0] = x[1]; y[0] = y[1]; | |
x[1] = temp[0]; y[1] = temp[1]; | |
} | |
return (y[0] < 0)?(N_ALF+y[0]):y[0]; | |
} | |
char cifra(char c){ | |
return (((c - 'a')*A+B)%N_ALF)+'a'; | |
} | |
char decifra(char c){ | |
int inv = inversa_modular(A, N_ALF); | |
return (((N_ALF+(c - 'a')-B)*inv)%N_ALF)+'a'; | |
} | |
//ponteiro para a função | |
char (*func) (char); | |
int main (int argc, char *argv[]) { | |
FILE* ifile; | |
char buffer[BUFFER_SIZE]; | |
if(argc != 3 && argc != 2){ | |
printf(USAGE, argv[0]); | |
return -1; | |
}else{ | |
if(strcmp(argv[1], CMD_DECIFRA) == 0){ | |
func = decifra; | |
}else{ | |
func = cifra; | |
} | |
if(argc == 3){ | |
//arquivo de entrada | |
ifile = fopen(argv[2], "r"); | |
}else if(argc == 2){ | |
//entrada padrão | |
ifile = stdin; | |
} | |
} | |
int n_data; | |
while((n_data = fread(buffer, sizeof(char), BUFFER_SIZE, ifile))){ | |
int i; | |
//altera o buffer | |
for(i=0; i<n_data; i++){ | |
if(buffer[i] >= 'a' && buffer[i] <= 'z') | |
buffer[i] = func(buffer[i]); | |
} | |
for(i=0; i<n_data; i++){ | |
printf("%c", buffer[i]); | |
} | |
} | |
fclose(ifile); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment