Search code examples
ctoupper

How this custom toupper() function works?


I've seen following program that uses custom toupper() function.

#include <stdio.h> 
void my_toUpper(char* str, int index)
{
    *(str + index) &= ~32;
}
int main()
{
    char arr[] = "geeksquiz";
    my_toUpper(arr, 0);
    my_toUpper(arr, 5);
    printf("%s", arr);
    return 0;
}

How this function works exactly? I can't understand logic behind it. It will be good If someone explains it easily.


Solution

  • Following the ASCII table, to convert a letter from lowercase to UPPERCASE, you need to subtract 32 from the ASCII value of the lowercase letter.

    For the ASCII values representing the lowercase letters, subtracting 32, is equal to ANDing ~32. That is what being done in

     *(str + index) &= ~32;
    

    It takes the value of the indexth member from the str, subtract 32 (bitwise AND with ~32, clears the particular bit value) and stores it back to the same index.

    FWIW, this is a special case of "resetting" a particular bit to get the result of actually subtracting 32. This "subtraction" works here based on the particular bit representation of the lowercase letter ASCII values. As mentioned in the comments, this is not a general way of subtraction, as this "resetting" logic won't work on any value for subtraction.

    Regarding the operators used,

    • &= is assignment by bitwise AND
    • ~ is bitwise NOT.

    Note: This custom function lacks the error check for the (in)valid value present in str. You need to take care of that.