^ = 32背后的想法是什么,将小写字母转换为大写字母,反之亦然? [英] What is the idea behind ^= 32, that converts lowercase letters to upper and vice versa?

查看:78
本文介绍了^ = 32背后的想法是什么,将小写字母转换为大写字母,反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决代码部队方面的一些问题.通常,我首先检查该字符是大写还是小写英文字母,然后减去或加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 << '\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?

推荐答案

让我们看一下二进制的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆