theking7's blog

By theking7, history, 12 months ago, In English

code :

// Converting Upper to lower and Vice Versa 1) If we do 1 left shift 5 and if we toggle the bits and take a '&' of it, we can turn the lower case to Upper Case.

cout << char('c' & ~( 1 << 5)) << endl;

2) If we do 1 left shift 5 and if we take a '|' of it, we can turn the Upper case to Lower Case.

cout << char('C' | 1 << 5) << endl;

3) More Cooler Trick — i) 1 left shift 5 can be switched with the ASCII value of space i.e. ' '.

cout << char('c' & ~(' ')) << endl;
cout << char('C' | ' ') << endl;
 
 
 
 
  • Vote: I like it
  • +59
  • Vote: I do not like it

»
12 months ago, # |
  Vote: I like it +94 Vote: I do not like it

I was using

char c;
c ^= ' ';

It change "case" of letter c. If letter was lowercase, it is now uppercase and if it was uppercase, it is now lowercase.

»
12 months ago, # |
  Vote: I like it +11 Vote: I do not like it

Even cooler is that ^= 1 to flip the bit works for strings as well.

»
9 months ago, # |
  Vote: I like it -8 Vote: I do not like it

And this one is the coolest.

char uppercase(char ch) {
    return c >= 97 && c <= 123 ? ch & 0xDF : ch;
}

char lowercase(char ch) {
    return c >= 65 && c <= 91 ? ch | 0x20 : ch;
}
»
9 months ago, # |
  Vote: I like it 0 Vote: I do not like it

You can xor the character with 32 to change it from upper to lower or the opposite. Check this.