Tuesday, June 20, 2017

C program to encode and decode string

Recently I get introduced to too many technology WhatsApp groups which talks about software development, basic electronics, robotics, AI and many more. It really helps me to know what is going in other areas instead of browsing for news. Also it is happy to be in places where people help each other.

Below is one question someone threw to a groups and I could do something after a week.

Write C program for self defined codec

1.Get a string of chars from user.
2. Convert string to array of chars (each char has value 0~255)
3.Define a lookup table (LUT) and an algorithm to encode the char values.
4.Use the LUT and algoithm from step 3 to encode the array of chars.
5.Output the encoded array of chars.
6.Decode the encoded array of chars.
7.Output the decoded array of integers to prove that your algorithm can decode.

I seriously programmed in C when I was in college and during my job seeking. After I landed in .Net world, there were less than 5 scenarios where I had to look or code in C/C++. Yes the big trouble was with pointers. Also comparing C#, I felt driving 80's model Ambassador car when programmed in C. Enough talks. Below is the code

#include < stdio.h >
char LUT[26] = "QRSTUVWXYZABCDEFGHIJKLMNOP";

int getLocationFromLUT(char c) {
  int i = 0;
  while (i < 26) {
    if (LUT[i] == c) return i;
    else i++;
  }
  return -1;
}

char * encode(char * str) {
  int i = 0;
  while (str[i] != '\0') {
    int locationInAlphabet = str[i] - 65;
    str[i++] = LUT[locationInAlphabet];
  }
  return (str);
}
char * decode(char * str) {
  int i = 0;
  while (str[i] != '\0') {
    int location = getLocationFromLUT(str[i]);
    str[i++] = location + 65;
  }
  return (str);
}
int main() {
  printf("Enter string to encode (caps & max len 64)\n");
  char word[64];
  scanf("%s", word);

  char * encoded = encode( & word[0]);
  printf("Encoded string %s\n", encoded);

  char * decoded = decode(encoded);
  printf("Decoded string %s\n", decoded);
  return 0;
}

So simple isn't it. Took me around 2 hrs to get the code completed.

It can be run in browser using tutorialspoint online environment. Technically it not in browser, browser just acts as console. I used this environment to write this code.
http://www.tutorialspoint.com/compile_c_online.php?PID=0Bw_CjBb95KQMU0tIWi1qcEJUUUk

No comments: