🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Encode Decode Strings in C
Build a shift cipher and a substitution table cipher in C, and learn how lookup tables work in embedded programs.
What You Will Learn
- How character arithmetic turns letters into numbers and back
- How to write one function that encodes and decodes with a shift key
- How to build and validate a 26 letter substitution table
- How to derive the decoder table instead of typing it
- Why table lookups are common in embedded C programming
Prerequisites
- Lectures cp9_48 to cp9_50
- ASCII and the char type
- Arrays, the remainder operator and ctype.h
Encoding text is the classic way to practise string indexing, character arithmetic and lookup tables all in one small program. In this lecture of our free C programming course you will learn how to encode and decode strings in C with two techniques: a shift cipher, where every letter moves a fixed distance along the alphabet, and a substitution table, where every letter has a hand-picked partner. The same ideas appear in embedded C programming whenever you map codes to characters: seven-segment displays, keypad scan codes, base64 style transfer encodings and protocol opcode tables.
Not real security. Both ciphers here are teaching tools. Anyone can break them in minutes. For protecting real data, use a vetted cryptography library with modern algorithms, never your own scheme.
Character Arithmetic: The Idea Behind Every Cipher
In C a character is a small integer. The letters a to z have consecutive codes in ASCII, which means c - 'a' turns a lowercase letter into a number from 0 to 25. Add a key, wrap around with the remainder operator, add 'a' back, and you have a shifted letter. The remainder is what makes z followed by a work.
Uppercase letters need their own base, otherwise a capital would jump into the lowercase range. Characters that are not letters, such as digits, spaces and punctuation, pass through unchanged.
Shift Cipher in C: Encode and Decode with One Function
The first exercise asks for a program that encodes text by replacing each character with another one a fixed distance away and then decodes it again. The elegant solution uses one function for both directions. Decoding with a key of 3 is simply encoding with a key of -3, because moving back is the same as moving forward by the complement.
Normalising the Key
A key can be negative or larger than 26. We reduce it first: key %= 26, and if the result is negative, add 26. Now every key is in the range 0 to 25 and the main expression never produces a negative offset. This small step is why a key of 29 behaves exactly like a key of 3 in the output below.
#include <stdio.h>
#include <ctype.h>
static void shift_text(char *s, int key)
{
key %= 26;
if (key < 0)
key += 26;
for (; *s != '\0'; s++) {
if (islower((unsigned char)*s))
*s = (char)('a' + (*s - 'a' + key) % 26);
else if (isupper((unsigned char)*s))
*s = (char)('A' + (*s - 'A' + key) % 26);
}
}
int main(void)
{
char msg[] = "Firmware v2 ready, zebra!";
printf("plain : %s\n", msg);
shift_text(msg, 3);
printf("encoded : %s\n", msg);
shift_text(msg, -3);
printf("decoded : %s\n", msg);
shift_text(msg, 29); /* 29 behaves like 3 */
printf("key 29 : %s\n", msg);
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o shift_cipher shift_cipher.c
./shift_cipher
plain : Firmware v2 ready, zebra!
encoded : Ilupzduh y2 uhdgb, cheud!
decoded : Firmware v2 ready, zebra!
key 29 : Ilupzduh y2 uhdgb, cheud!
Notice what happened to the unusual characters. The z of zebra wrapped to c, the capital F became I, and the digit 2, the spaces, the comma and the exclamation mark all stayed put. Decoding restored the original, and the last line shows that a key of 29 matches a key of 3.
| Key | Effect on b | Reason |
|---|---|---|
| 0 | b | No shift |
| 1 | c | One step forward |
| 25 | a | Equivalent to -1 |
| 26 | b | Full circle |
| -3 | y | Back three, wrapping below a |
Substitution Table: A Lookup-Based Cipher
The second exercise gives a table that pairs each letter of the alphabet with another letter. Instead of arithmetic, you simply look up the partner. A table indexed by c - 'a' turns encoding into one array access per character, and that is also how embedded firmware translates keypad codes or segment patterns, because a table lookup takes constant time and no branching.
Building the Decoder Automatically
Writing a second 26 letter table by hand invites typos. Instead, build the decoder from the encoder at start-up: for every position i, the cipher letter enc[i] maps back to 'a' + i. The rule is just one line inside a loop, and it guarantees that decoding is the exact inverse.
Validating the Table
A substitution table only works if it is a permutation: each of the 26 letters appears exactly once. If two plain letters shared the same cipher letter, decoding would be ambiguous. The program checks this with a small seen array before it does anything else, and refuses to run if the table is invalid.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
static const char enc_table[27] = "qwertyuiopasdfghjklzxcvbnm";
static char dec_table[27];
static int table_is_permutation(const char *t)
{
int seen[26] = {0};
for (int i = 0; i < 26; i++) {
if (t[i] < 'a' || t[i] > 'z' || seen[t[i] - 'a']++)
return 0;
}
return 1;
}
static void build_decoder(void)
{
for (int i = 0; i < 26; i++)
dec_table[enc_table[i] - 'a'] = (char)('a' + i);
dec_table[26] = '\0';
}
static void translate(char *s, const char *table)
{
for (; *s != '\0'; s++) {
unsigned char c = (unsigned char)*s;
if (islower(c))
*s = table[c - 'a'];
else if (isupper(c))
*s = (char)toupper((unsigned char)table[tolower(c) - 'a']);
}
}
int main(void)
{
char msg[] = "Embedded Systems 101";
if (!table_is_permutation(enc_table)) {
puts("bad key table");
return 1;
}
build_decoder();
printf("plain : %s\n", msg);
translate(msg, enc_table);
printf("encoded : %s\n", msg);
translate(msg, dec_table);
printf("decoded : %s\n", msg);
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o table_cipher table_cipher.c
./table_cipher
plain : Embedded Systems 101
encoded : Tdwtrrtr Lnlztdl 101
decoded : Embedded Systems 101
Check the first letter by hand: E is the fifth letter, index 4, and enc_table[4] is t, so the capital E becomes T. Case is preserved by converting the table entry back to uppercase, and the digits 101 are untouched.
Shift Cipher Versus Substitution Table
| Property | Shift cipher | Substitution table |
|---|---|---|
| Key | One small number | 26 letter permutation |
| Number of keys | 25 useful ones | 26 factorial, about 4 times ten to the 26th |
| Needs extra memory | No | Two 26 byte tables |
| Decode | Encode with the negative key | Use the inverse table |
| Typical embedded use | Counters, rolling codes, wrap-around indexes | Keypad maps, display fonts, opcode names |
| Strength as a cipher | Trivial to break | Still breakable by letter frequency |
Common Mistakes and Troubleshooting
- Negative offsets. In C the remainder of a negative number can be negative. Normalise the key before the main expression.
- Shifting everything. If digits and punctuation change too, you probably forgot the
islowerandisuppertests. - Mixing case bases. Using
'a'for a capital letter pushes it into the wrong range. - Using a table that is not a permutation. One duplicated letter makes decoding impossible. Validate at start-up.
- Using a plain
charas an array index. Convert withc - 'a'after confirming the letter is in range, so you never index outside the table. - Forgetting the cast for ctype calls. Cast to
unsigned charas shown in the code.
Best Practices, Performance and Security
- Both encoders are O(n) and allocate nothing, which is ideal for a small microcontroller.
- Make tables
static constso the compiler can place them in flash and save RAM; only the generated decoder needs RAM. - Keep the key outside the algorithm so tests can try many keys without recompiling.
- Never invent encryption for real products. Use an audited library and standard algorithms for any data that matters.
- Test round trips: encode then decode must return the original for every printable character, not only letters.
Practice Challenges
- Add a function that tries all 25 shifts on an unknown message and prints each result, then find the readable one.
- Make the table cipher handle digits by extending the table to 36 entries.
- Write a test that proves encoding followed by decoding returns the original string for a table you create by rotating the alphabet.
Key Takeaways
- A letter becomes a number with
c - base, and wrap-around uses% 26. - Decoding with a shift cipher is encoding with the negative key, once the key is normalised.
- A substitution table turns encoding into one array lookup per character.
- Build the decoder from the encoder and validate that the table is a permutation.
- These ciphers teach indexing and tables; they are not cryptography.
Conclusion
Encoding exercises are small, but they train the exact skills that firmware needs: indexing arrays from characters, wrapping counters, and building tables that are checked rather than trusted. If you can explain why the remainder operator handles the wrap and why the decoder is derived rather than typed, you understand the lecture.
Next in this free C tutorial we sort the letters of a word, build abbreviations and extract substrings, three jobs that combine loops, comparisons and careful bounds checking in embedded C programming.
Frequently Asked Questions
How do I encode a string in C by shifting letters?
Convert each letter to a number from 0 to 25 with c - 'a', add the key, take the remainder modulo 26, then add 'a' back. Use 'A' as the base for capitals.
How do I decode a shifted string?
Call the same function with the negative key. Normalising the key into 0 to 25 makes this safe.
What is a substitution table cipher?
A 26 entry array where each plain letter index holds its cipher letter. Encoding is a lookup; decoding uses the inverse table.
Why must the table be a permutation?
If a cipher letter appeared twice, you could not tell which plain letter it came from. Each letter must appear exactly once.
Are these ciphers secure?
No. They are exercises in indexing and tables. Use a proper cryptography library for anything that needs real security.
Where do lookup tables appear in embedded programming?
Display fonts, keypad scan maps, CRC tables and opcode names all use the same table-lookup idea you practised in this free embedded C course lecture.
Keep Going With the Free Embedded C Course
EmbeddedPathashala teaches embedded C programming, Linux kernel development and device drivers for free. Pick the next lecture and keep your streak going.

2 Comments