Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a char to uppercase without using toupper function

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')
like image 408
J3soon Avatar asked Dec 19 '22 21:12

J3soon


2 Answers

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')
like image 95
Barmar Avatar answered Dec 21 '22 10:12

Barmar


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 ifs. I strongly suggest using std::toupper or a more unicode-aware version.

like image 41
rubenvb Avatar answered Dec 21 '22 10:12

rubenvb