^= 32 背后的想法是什么,将小写字母转换为大写字母,反之亦然? [英] What is the idea behind ^= 32, that converts lowercase letters to upper and vice versa?
问题描述
我正在解决一些关于 codeforces 的问题.通常我首先检查字符是大写还是小写英文字母,然后减去或添加 32
将其转换为相应的字母.但我发现有人做 ^= 32
做同样的事情.这是:
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 << '
'; // foo is A, and bar is a
我已经搜索了对此的解释,但没有找到.那么为什么会这样呢?
I have searched for an explanation for this and didn't find out. So why this works?
推荐答案
我们来看看二进制的ASCII码表.
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
而 32 是 0100000
这是小写和大写字母之间的唯一区别.所以切换那个位会切换字母的大小写.
And 32 is 0100000
which is the only difference between lowercase and uppercase letters. So toggling that bit toggles the case of a letter.
这篇关于^= 32 背后的想法是什么,将小写字母转换为大写字母,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!