Recently I've seen a piece of code that converts a char to lowercase, and if it's already a lowercase it stays the same.
char c = 'A';
c |= ' ';
//c -> 'a'
I'm trying to write a code that can convert a char to uppercase without using the toupper function.
Currently the most simple way that i can think of is the code below.
char c = 'a';
c = (c | ' ') - ' ';
//c -> 'A'
So I'm wondering if there's a code which is more straightforward than this, and can achieve the same results.
Any help is appreciated.
Quick explanation of the first code block
Char | ASCII Code
' ' | 13
'A' | 65
'a' | 97
and the or
operator for bit manipulation
01000001 (char 'A')
Or 00100000 (char ' ')
= 01100001 (char 'a')
----------------------
01100001 (char 'a')
Or 00100000 (char ' ')
= 01100001 (char 'a')
The inverse operation of OR
is AND
with the complement.
char c = 'a';
c &= ~' ';
Explanation:
01100001 (char 'a')
AND 11011111 (~ char ' ')
= 01000001 (char 'A')