Search code examples
casciiuppercaselowercase

Convert lowercase to uppercase using ASCII


I am trying to convert all lowercase to uppercase letter, using the ASCII table! It is very easy to deal and i have figured out the code. Problem is, that if there is a space between the words, then the program will only change the first word and after the space it will not print anything.

Example
Word: Andreas Gives: ANDREAS
Word: TeSt123Ha Gives: TEST123HA
BUT!!!
Word: Hello 45 Gives: HELLO
after the space it prints nothing!

I know that the space in ASCII table is equal to 32, and in my code i tell the program that if the current code that you are reading is not between 97 and 122, then don't perform any changes!

But it is still not working!

char currentletter;
int i;

for (i=0; i<49; i++)    
{
    currentletter = str[i];

    if ((currentletter > 96) && (currentletter < 123))
    {
        char newletter;
        newletter = currentletter - 32;
        str[i] = newletter;
    }
    else
    {
        str[i] = currentletter;
    }
}
printf("%s\n", str);

Solution

  • flipping the 5th lowest bit should help.

    Each lowercase letter is 32 + uppercase equivalent. This means simply flipping the bit at position 5 (counting from least significant bit at position 0) inverts the case of a letter. https://web.stanford.edu/class/cs107/lab1/practice.html

    char *str;
    int str_size = sizeof(str);
    
    for(int i=0; i<str_size;i++){
       if((str[i]>96) && (str[i]<123)) str[i] ^=0x20;
    }