Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, most efficient way to change uppercase to lowercase and vice versa without condition branching

Tags:

c++

ascii

We have single character Chr on input. Output must be lowercase of Chr if Chr is uppercase and vice versa.

Trivial realization using if else statement:

if(Chr>='a' && Chr<='z') cout<<(unsigned char)(a-32);
else cout<<(unsigned char)(a+32);

Could you propose solution without any condition branching?

Something like Chr + 32*(<sign of>(Chr - 'a'))?

Update: I kept ASCII in mind when asked this question.

like image 980
Alan Kazbekov Avatar asked Dec 10 '22 12:12

Alan Kazbekov


1 Answers

If your characters are using the ASCII character set you can xor with the value 32 to flip between upper and lower case.

char switchCase(char letter)
{
    return letter ^ 32;
}
like image 177
Colin Avatar answered May 19 '23 19:05

Colin