What are Uppercase and Reverse C Strings- Best C Language Course For Beginners

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Strings

Uppercase and Reverse C Strings

Change string case the right way and reverse text in place, with the ASCII bit trick explained.

Two of the most common string chores in any program are changing letter case and reversing text. Learning to convert a string to uppercase in C teaches you how characters are really stored as numbers, and reversing teaches you to modify memory in place without a second buffer. This lecture of our free C programming course covers both with original programs, explains the ASCII trick behind case conversion, and ends with practical uses in embedded C programming. Everything compiles with plain gcc and nothing is copied from a textbook.

What You Will Learn

  • Why subtracting 32 from every character is a bug
  • Three correct ways to convert a string to uppercase in C
  • The single bit that separates a letter from its capital in ASCII
  • Why you cannot modify a string literal and what to use instead
  • How to reverse a string in place with two indexes and a swap
  • Where these skills show up in firmware: command matching and number formatting

Prerequisites

You need char arrays, pointers to char, strlen from string.h, and the ctype.h header. If you can explain the difference between a char array and a pointer to a string literal, you are ready. This lecture is part of the free C tutorial strings chapter.

Convert a String to Uppercase in C: Why 32 Is Not Enough

In ASCII the lower-case letter a has code 97 (0x61) and the capital A has code 65 (0x41). The gap is exactly 32 (0x20), so many first attempts simply subtract 32 from every character. That works only for letters. Watch what it does to a mixed string.

#include <stdio.h>

int main(void)
{
    const char *text = "Ab3x";

    printf("%-5s %-7s %-7s\n", "char", "before", "after");
    for (int i = 0; text[i] != '\0'; i++) {
        unsigned char before = (unsigned char)text[i];
        unsigned char after  = (unsigned char)(before - 32);   /* blind subtraction */
        printf("'%c'   0x%02X    0x%02X\n", before, before, after);
    }
    return 0;
}

Compile and run it:

gcc -std=c17 -Wall -Wextra -o case_bug case_bug.c
./case_bug
char  before  after  
'A'   0x41    0x21
'b'   0x62    0x42
'3'   0x33    0x13
'x'   0x78    0x58

The lower-case letters b and x became B and X, which is correct. But the capital A turned into 0x21, an exclamation mark, and the digit 3 turned into 0x13, an invisible control character. A blind subtraction corrupts anything that is not a lower-case letter. The fix is a gate that lets only a to z through.

Safe conversion needs a gate: only ‘a’ to ‘z’ may change
0 to 9 (0x30-0x39)A to Z (0x41-0x5A)a to z (0x61-0x7A)
digits and capitals must pass through untouched, only the highlighted range is converted

The Bit That Lets You Convert a String to Uppercase in C

Look at the two codes in binary. Only bit 5 is different, which is why the gap is 32. Setting that bit gives lower case, clearing it gives upper case. The designers of ASCII chose this layout on purpose so that hardware as simple as a single gate could change case.

ASCII secret: a lower-case letter differs from its capital in bit 5 only
bit position: 7 6 5 4 3 2 1 0
‘a’ = 0x61
01100001
‘A’ = 0x41 (clear bit 5, subtract 0x20 = 32)
01000001

Three Methods to Convert a String to Uppercase in C

The program below converts the same text with three different functions and prints all results so you can compare them. The test string deliberately contains capitals, digits, a space and an underscore.

#include <ctype.h>
#include <stdio.h>
#include <string.h>

static void upper_range(char *s)
{
    for (; *s != '\0'; s++)
        if (*s >= 'a' && *s <= 'z')
            *s = (char)(*s - ('a' - 'A'));
}

static void upper_mask(char *s)
{
    for (; *s != '\0'; s++)
        if (*s >= 'a' && *s <= 'z')
            *s = (char)(*s & ~0x20);          /* clear bit 5 */
}

static void upper_ctype(char *s)
{
    for (; *s != '\0'; s++)
        *s = (char)toupper((unsigned char)*s);
}

int main(void)
{
    const char *original = "Embedded C 2026 uart_tx";
    char a[32], b[32], c[32];

    strcpy(a, original);
    strcpy(b, original);
    strcpy(c, original);

    upper_range(a);
    upper_mask(b);
    upper_ctype(c);

    printf("original : %s\n", original);
    printf("range    : %s\n", a);
    printf("bit mask : %s\n", b);
    printf("ctype    : %s\n", c);
    return 0;
}
original : Embedded C 2026 uart_tx
range    : EMBEDDED C 2026 UART_TX
bit mask : EMBEDDED C 2026 UART_TX
ctype    : EMBEDDED C 2026 UART_TX

All three agree, but they are not equal in quality.

MethodHow it worksStrengthWeakness
Range check and subtractIf c is between a and z, subtract the gap computed from the two lettersClear and portable for ASCII-based systemsAssumes letters are contiguous in the character set
Bit maskIf c is a to z, clear bit 5 with a bitwise ANDOne instruction, popular in firmwareValid only because of ASCII layout, and only after the range gate
toupper from ctype.hThe library decides, honouring the current localeMost portable and self-explainingA function call per character, argument must be cast to unsigned char

For application code that must run anywhere, use toupper. For a bootloader command line where you know the data is ASCII and every byte counts, the range check or the mask is perfectly reasonable. What you must never do is apply the bit mask without the range check, because clearing bit 5 of a digit or a punctuation mark changes it into something else.

Always cast for ctype functions. toupper, tolower, isalpha and friends take an int that must be EOF or a value representable as unsigned char. If a plain char is negative, as it can be for bytes above 127 on many platforms, the behaviour is undefined. Write toupper((unsigned char)c).

You Cannot Modify a String Literal

All three functions modify the string they receive, so the string must live in writable memory. These two declarations look alike but behave very differently:

char  writable[] = "uart";   /* a copy in an array, safe to modify */
char *literal    = "uart";   /* points at the literal, do not modify */

Changing a character through the second pointer is undefined behaviour. On a desktop it usually crashes because the literal sits in read-only memory. On a microcontroller the literal is often stored in flash, where a write silently does nothing or raises a fault. That is why the demo program copies the original into three arrays with strcpy before converting.

Reverse a String in Place

To reverse text without a second buffer, keep one index at the start and one at the end, swap the two characters, and move both inward. When the indexes meet, every pair has been swapped exactly once.

Reverse in place: swap the outer pair, then move inward
start
firmware
swap index 0 and 7
eirmwarf
swap index 1 and 6
errmwaif
swap index 2 and 5
eramwrif
swap index 3 and 4, indexes have met, done
erawmrif
#include <stdio.h>
#include <string.h>

static void print_reversed(const char *s)
{
    size_t n = strlen(s);

    while (n > 0)
        putchar(s[--n]);
    putchar('\n');
}

static void reverse_in_place(char *s)
{
    size_t n = strlen(s);

    if (n < 2)
        return;
    for (size_t i = 0, j = n - 1; i < j; i++, j--) {
        char tmp = s[i];
        s[i] = s[j];
        s[j] = tmp;
    }
}

int main(void)
{
    const char *label = "Pathashala";
    char buf[] = "firmware";
    char one[] = "x";
    char none[] = "";

    printf("printed backwards : ");
    print_reversed(label);

    reverse_in_place(buf);
    reverse_in_place(one);
    reverse_in_place(none);

    printf("in place          : %s\n", buf);
    printf("one char          : %s\n", one);
    printf("empty             : [%s]\n", none);
    return 0;
}

Run it the same way. The first line prints the word backwards without changing it. The next lines reverse arrays in place, including the boundary cases of one character and zero characters.

printed backwards : alahsahtaP
in place          : erawmrif
one char          : x
empty             : []

The guard if (n < 2) return; serves two purposes. It skips needless work for strings that cannot change, and it protects the expression n - 1, which would wrap around for an empty string because size_t is unsigned. The loop condition i < j stops before the pointers cross, so the middle character of an odd-length string is never swapped with itself.

Where This Matters in Embedded Work

  • Command matching. A user may type set, Set or SET on a serial console. Converting the command word to one case before comparing it makes the parser forgiving without extra branches.
  • Number to text. The classic way to print an integer without printf is to extract digits from the least significant end, which produces them backwards, and then reverse the buffer in place.
  • Hex dumps and identifiers. Device identifiers and MAC addresses are often displayed in capitals, so a quick uppercase pass cleans them up.
  • Protocol keywords. Many text protocols, such as AT command sets, define keywords case-insensitively.

A related caution: reversing bytes works for single-byte ASCII text. UTF-8 characters can take two to four bytes, and reversing them byte by byte produces invalid sequences. Likewise toupper only understands the characters of the current single-byte locale.

Common Mistakes

MistakeResultFix
Subtracting 32 without checking the rangeDigits and capitals are corruptedGate with c >= ‘a’ && c <= ‘z’
Modifying a pointer to a string literalCrash or silent failureCopy into a char array first
Applying the bit mask to every characterDigits and symbols changeMask only after the range test
Calling toupper with a plain charUndefined behaviour for negative valuesCast to unsigned char
Reversing with i <= jNeedless swap of the middle character with itselfUse i < j
Forgetting the empty-string caseUnsigned wrap-around of n – 1Return early when n is less than 2

Best Practices, Performance and Security

  • Pass the destination array and its size when you write conversion functions that produce a new string, so you can never overrun it.
  • Prefer an in-place version for tiny targets, and a copy-producing version when you must keep the original.
  • Both operations are O(n) with O(1) extra memory. Per-character function calls to toupper are cheap on a desktop and acceptable on most microcontrollers, but check the generated code in a hot path.
  • Never convert the case of data you will later compare in a security check (for example a path or a user name) without agreeing on exactly one canonical form first.
  • Always test the empty string, a one-character string and a string with digits, spaces and symbols.

Summary and Key Takeaways

  • ASCII lower-case and upper-case letters differ by 32, which is bit 5 (0x20).
  • To convert a string to uppercase in C, gate on a to z, then subtract 32, clear bit 5, or call toupper.
  • Literals are read-only, so convert a copy held in a char array.
  • Reverse in place with two indexes and a swap, stopping when they meet.
  • Guard empty and one-character strings, and cast arguments to unsigned char for ctype functions.

Conclusion

Case conversion and reversal look trivial, but they expose how C really treats text: as bytes with numeric codes, living in memory that may or may not be writable. Once you can convert a string to uppercase in C without corrupting digits, and reverse it without extra memory, you are ready for loops that count and classify characters. The next lecture of this free C programming course counts the words in a line of text, and it uses exactly the character-class tools you just practised.

Frequently Asked Questions About Uppercase and Reversing Strings in C

How do I convert a string to uppercase in C?

Loop over the characters and apply toupper from ctype.h to each one, casting to unsigned char. Alternatively test for a to z and subtract 32 or clear bit 5.

Why can’t I just subtract 32 from every character?

Only lower-case letters are 32 above their capitals. Subtracting from digits, symbols or capitals produces unrelated characters.

Why does changing a string literal crash my program?

String literals usually sit in read-only memory. Modifying them is undefined behaviour. Declare a char array initialised from the literal instead.

What is the fastest way to reverse a string in C?

Swap characters from both ends moving inward. It runs in O(n) time and needs no extra memory.

Does toupper work on non-English letters?

toupper only handles characters according to the current single-byte locale. It does not understand multi-byte UTF-8 sequences.

What does & ~0x20 do to a character?

It clears bit 5, turning a lower-case ASCII letter into its capital. Apply it only to letters, never to digits or symbols.

Is it safe to reverse a UTF-8 string byte by byte?

No. Multi-byte characters would be split and reversed into invalid sequences. Reverse by character instead.

Practise Embedded C for Free

Small string tools like these appear in every serial console and bootloader. Keep learning with the rest of the free C tutorial.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →