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 &= ~' ';
DEMO
Explanation:
01100001 (char 'a')
AND 11011111 (~ char ' ')
= 01000001 (char 'A')
A very intuitive and semi-readable way is to use character subtraction:
Live on coliru
#include <iostream>
char uppercase(char bla)
{
return bla -('a'-'A');
}
int main()
{
std::cout << uppercase('a') << '\n';
}
Note this only works on a-z
, and the rest will need special treatment with some if
s. I strongly suggest using std::toupper
or a more unicode-aware version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With