The Cryptic Text Encoder

In last week’s Lesson, I waxed on about how a text message can be concealed in a delightful manner, making it not look like a text message at all. To get to that point, you must write some code that translates plain text into the values desired.

For this type of encryption, the code munches through a string of text in this manner:

  1. The first character of the string is output as its ASCII value.
  2. Obtain the next character of the string.
  3. Subtract the previous character’s ASCII value
  4. Output the result.
  5. If the newline is encountered, stop, otherwise repeat at Step 2.

Here’s the code I concocted:

#include <stdio.h>

#define SIZE 32

int main()
{
    char input[SIZE];
    signed int x,ch;

    printf("Text: ");
    fgets(input,SIZE,stdin);

    x = 0;
    printf("Translation:\n%d",input[x]);
    while( (ch = input[x]) )
    {
        x++;
        printf(", %d",input[x] - ch);
        if( ch == '\n' )
            break;
    }
    printf("\nCount: %d\n",x+1);
    
    return(0);
}

Lines 10 and 11 fetch input. The fgets() function is used, so the string is terminated by a newline or null character, but most likely the newline.

Line 14 outputs the initial results, which should always be at least one character long: Even if no text is input, the character at element input[x] (where x is equal to zero) is the newline. That character is output as ASCII code 10 and the program stops. Otherwise, the entire string is processed.

The while loop at Line 15 plows through the string as long as the null character at input[x]. This character is saved in variable ch. Note how the assignment is enclosed in parentheses? The character fetched is generated as the while loop’s termination value; the null character ends the loop.

Lines 17 and 18 test for the newline. If found, the loop is broken.

Variable x is incremented at Line 19, referencing the next character in the string.

At Line 20, the value of the previous character, ch, is subtracted from the current character, input[x]. This value is output. The loop repeats.

Here’s a sample run:

Text: Secret, sneaky text.
Translation:
83, 18, -2, 15, -13, 15, -72, -12, 83, -5, -9, -4, 10, 14, -89, 84, -15, 19, -4, -70, -36
Count: 21

The count value was added (at Line 22 in the code) to reference how many bytes are in the string. This value helps when writing the decoder because the values generated have no end marker. As I wrote in last week’s Lesson, the encrypted values can be positive, negative, or zero. If I assigned a specific value as the end marker, then I wouldn’t need the count. But as this code is written (encrypted and decrypted), the count value is used instead.

Leave a Reply