Here we will build a program to showcase an efficient way to convert a char from upper to lower and vice versa in C in a single line. Below is one example which explains how bitwise operators help in efficient programming and also convert the given alphabet from one case to another.
Example:
C
#include <stdio.h>
#define convert_case(c) c^(1<<5)
#define to_lower(c) c|(1<<5)
#define to_upper(c) c&~(1<<5)
int main()
{
char ch_u = 'S' ;
char ch_l = 's' ;
char ch = 's' ;
printf ( "convert: %c, to_lower: %c, to_upper: %c\n" ,
convert_case(ch), to_lower(ch_u), to_upper(ch_l));
return 0;
}
|
Outputconvert: S, to_lower: s, to_upper: S
Explanation:
- The difference between upper case and lower case in ASCII is 32 (‘A’ – ‘a’)
- So, in the lower case of the alphabet character always 5th position is set (assuming little endian here)