Change case of a character (Using Bit Manipulation)
Lowercase to uppercase
Uppercase to lowercase
Using Bit manipulation we can change case of a character very easily and efficiently, as we know every character is stored in memory as their ASCII code which is an Integer value
Here is Binary representation of Some ALPHABETs in uppercase as well as in their lowercase.
Alphabet ASCII code Binary form
A 65 1000001
a 97 1100001
B 66 1000010
b 98 1100010
Z 90 1011010
z 122 1111010
If we look carefully we will find that only 5th bit (considering 0 based indexing) is different in the binary representation of Uppercase and lowercase of a particular character (Alphabet).
Converting lowercase to uppercase
We need to clear the 5th bit of the given character to make it in uppercase.
To clear 5th bit in the given character, we can use BITWISE AND ( & ) operator as follow
char = char & (~(1 << 5));
it is equivalent to...
char = char & 95
95 is ASCII value of '_' ( Underscore)
so we can write it as
char = char & '_';
Let's take char
'a' = 97 ( 1100001 in binary )
'_' = 95 ( 1011111 in binary )
a & '_' = 65 ( 1000001 in binary )
And 65 is ASCII code for 'A' which is uppercase version of 'a'
Converting uppercase to lowercase
We need to set the 5th bit of the given character to make it in lowercase.
To set 5th bit in the given character we can use BITWISE OR (|) operation as follow: char = char | ( 1 << 5 );
Let's take char
A = 65 ( 1000001 in binary )
(1 << 5 ) = 32 ( 0100000 in binary )
A | 32 = 97 ( 1100001 in binary )
And 97 is ASCII code for 'a' which is lower case version of A