What is the idea behind ^= 32, that converts lowercase letters to upper and vice versa?

  • A+
Category:Languages

I was solving some problem on codeforces. Normally I first check if the character is upper or lower English letter then subtract or add 32 to convert it to the corresponding letter. But I found someone do ^= 32 to do the same thing. Here it is:

char foo = 'a'; foo ^= 32; char bar = 'A'; bar ^= 32; cout << foo << ' ' << bar << '/n'; // foo is A, and bar is a 

I have searched for an explanation for this and didn't find out. So why this works?

 


Let's take a look at ASCII code table in binary.

A 1000001    a 1100001 B 1000010    b 1100010 C 1000011    c 1100011 ... Z 1011010    z 1111010 

And 32 is 0100000 which is the only difference between lowercase and uppercase letters. So toggling that bit toggles the case of a letter.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: