Created
December 3, 2022 21:57
-
-
Save josephcagle/7fa12c7b6f4c08dbde33f1f7f831a4a0 to your computer and use it in GitHub Desktop.
-- .-. .-- .- - ... --- -. -.-. --- -- . .... . .-. .
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 <stdlib.h> | |
#include <stdbool.h> | |
#include <string.h> | |
#include <ctype.h> | |
void printEncoded(char[]); | |
void printDecoded(char[]); | |
int main(int argc, char *argv[]) | |
{ | |
const int BUF_LEN = 1024; | |
char inputLine[BUF_LEN]; | |
char op; | |
do { | |
printf("Choose operation - [e]ncode or [d]ecode: "); | |
scanf(" %c", &op); | |
} while (op != 'e' && op != 'd'); | |
printf("Type ctrl-C or ctrl-D to quit.\n"); | |
while (fgets(inputLine, BUF_LEN, stdin) != NULL) { | |
if (inputLine[strlen(inputLine)-1] == '\n') | |
inputLine[strlen(inputLine)-1] = '\0'; | |
if (op == 'e') | |
printEncoded(inputLine); | |
else | |
printDecoded(inputLine); | |
} | |
return 0; | |
} | |
const char UNENCODED[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890"; | |
const char *ENCODED[] = { | |
".-", // A | |
"-...", // B | |
"-.-.", // C | |
"-..", | |
".", | |
"..-.", | |
"--.", | |
"....", | |
"..", | |
".---", | |
"-.-", | |
".-..", | |
"--", | |
"-.", | |
"---", | |
".--.", | |
"--.-", | |
".-.", | |
"...", | |
"-", | |
"..-", | |
"...-", | |
".--", | |
"-..-", | |
"-.--", | |
"--..", // Z | |
" ", | |
".----", | |
"..---", | |
"...--", | |
"....-", | |
".....", | |
"-....", | |
"--...", | |
"---..", | |
"----.", | |
"-----" | |
}; // should be same length as UNENCODED | |
void printEncoded(char inputLine[]) { | |
for (int i=0; i<strlen(inputLine); i++) { | |
for (int j=0; j<strlen(UNENCODED); j++) { | |
if (toupper(inputLine[i]) == UNENCODED[j]) { | |
printf("%s ", ENCODED[j]); | |
} | |
} | |
} | |
printf("\n"); | |
} | |
void printDecoded(char inputLine[]) { | |
char encodedChunk[6]; | |
int chunkIndex = 0; | |
for (int i = 0; i < strlen(inputLine); i++) { | |
if (inputLine[i] != ' ') { | |
encodedChunk[chunkIndex++] = inputLine[i]; | |
} | |
// when we have a space or the end of the string | |
if (inputLine[i] == ' ' || i == strlen(inputLine)-1) { | |
if (inputLine[i] == ' ' && inputLine[i-1] == ' ') { // it's an encoded space character | |
printf(" "); // so print a space | |
while (inputLine[i+1] == ' ') // and progress up to the next non-space char | |
i++; | |
} | |
else { // just decode the last chunk and print | |
encodedChunk[chunkIndex] = '\0'; | |
for (int i=0; i<strlen(UNENCODED); i++) { | |
if (strcmp(encodedChunk, ENCODED[i]) == 0) { | |
printf("%c", UNENCODED[i]); | |
break; | |
} | |
} | |
chunkIndex = 0; | |
} | |
} | |
} | |
printf("\n"); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment