Change case using binary operators
A character can be converted to lower case using predefined functions like toupper() in C or toUpperCase in JAVA. But using these functions causes increase in time complexity. So when you have program complexity to worry about, the best way to go may be to use something inline, something as simple as a binary operator.
Interestingly, the English alphabet is arranged in such a position in the ASCII character set that it is easy to switch between an upper case character to a lower case and vice verse using a simple bit operation. To understand how, let’s take a look at the binary codes of the various characters in the word – ‘APPLe’:
Char Dec Bin
A 65 01000001
p 112 01110000
p 112 01110000
L 76 01001100
e 101 01100101
Now we see that the third bit from left(xxxxxxxx), in any of the 8-bit strings is 0 for UPPER case letters and 1 for lower case letters. And that’s where the catch is! All we have to do now is set this bit 1 if we need lower case letters and 0 if we need upper case letters. To do that, we use the binary OR operator. Simple and elegant solution. Isn’t it?
Implementation: Implementing this is also pretty straightforward. Here is some sample code that converts a character to lower case:
#include int main() { char capsLetter = ‘A’; // ’A’ in binary is 01000001 char mask = (char) 32; // 32 in binary is 00100000 printf(“The caps letter ‘%c’ ”, capsLetter); capsLetter | = mask; // ‘a’ in binary is 01100001 – result printf(“is converted to ‘%c’.”, capsLetter); return 0; }
Output:
The caps letter ‘A’ is converted to ‘a’.
You be also be interested to know about:
Let’s Connect!