I am trying to convert a char element from an char *argv[] array to lowercase from uppercase without using a function. I want to add 32 to the ascii integer.
When I try
This is from my own C++ library, but it works for C too as well.
Self-Optimized (Library Function)
// return the specified letter in lowercase
char tolower(int c)
{
// (int)a = 97, (int)A = 65
// (a)97 - (A)65 = 32
// therefore 32 + 65 = a
return c > 64 && c < 91 ? c + 32 : c;
}
// return the specfied letter in uppercase
char toupper(int c)
{
// (int)a = 97, (int)A = 65
// (a)97 - (A)65 = 32
// therefore 97 - 32 = A
return c > 96 && c < 123 ? c - 32 : c;
}
The return value is a printable char. However, some modern compilers may have optimized the code as this already if you're going to do the way below.
Readable
char tolower(int c)
{
return c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c;
}
char toupper(int c)
{
return c >= 'a' && c <= 'z' ? c - ('a' - 'A') : c;
}
Note that the difference between
aandAis a 32 constant.