# Simple Way to return char case

Some time ago, when i was in one of the Computer Science class, it was asked to make an function to switch case of a word.

I remember some solutions it were discussed with my colleagues, but none was as simple as the one I’ll gonna  show by the opposite it were very excruciating solutions.

Here’s is a simple tip: Before resolving the problem, try to understand the problem. The solution will appear.

So two simple functions to switch an given char to upper or lower case:

char toUpperCase(char c){
char t = c & 0x5F;
return ( t < ‘A’ || t > ‘Z’) ? c : t;
}
char toLowerCase(char c){
char t = c & 0x5F;
return ( t < ‘A’ || t > ‘Z’) ? c : c | 0x20;
}

OK, what it is done:

if we analyze the ascii table at bit level we will notice that:

‘A’ = 65 decimal = 0100 0001 binary

‘a’ = 97 decimal = 0110 0001 binary

‘Z’ = 90 decimal = 0101 1010 binary

‘z’ = 122 decimal = 0111 1010 binary

ok, we can see an pattern. the difference between uppercase and lowercase is 32 decimal (0010 0000 binary). if the want to change to uppercase we have to remove that bit and if we want to change to lowercase we have to set that bit.

Simple, isn’t it? But we question remains: What we should do if the char passed in argument isn’t a letter?

Hum, well i believe the best way is to return that char.

So we have to test the argument before changing the case. There are many ways to make the test, i choose the follow:

char t = c & 0x5F;
return ( t < ‘A’ || t > ‘Z’) ? c : …;

first i change the case of the receiving char to uppercase and save it in ‘t’. Since i will test this value if it is less than ‘A’ or greater than ‘Z’, i save in ‘t’ so it could get a little more performance. If ‘c’ isn’t a letter return c, else change the case.

Hope it could help…