C++ 十进制转二进制 ASCII码大小写转换
参考博客:<C++>十进制数转换成二进制显示
由于我要实现的功能局限于char类型,所以我根据参考写了一个。
1 #include <iostream>
2 using namespace std;
3 void binary(char num);
4 int main()
5 {
6 binary('a');
7 return 0;
8 }
9 void binary(char num)
10 {
11 char bitMask = 1 << 7;
12 for (int i = 0; i < 8; i++)
13 {
14 cout << (bitMask & num ? 1 : 0);
15 num = num << 1;
16 if(i == 3)
17 cout << ' ';
18 }
19 }运行结果如图:

为了美观,我在中间加了一个空格。接下来讨论ASCII码大小写转换的问题了,想必编程初学者都知道大写字母和小写字母之间相差的值是固定的。

大小写转换只需要加(+)或减(-)32就行了。但是,遇到不知道需要转换的字母是大写还是小写该怎么办?
请看如下代码:
1 #include <iostream>
2 using namespace std;
3 void binary(char num);
4 int main()
5 {
6 for (char big = 'A', small = 'a'; small <= 'z'; big++, small++)
7 {
8 cout << big << " ";
9 binary(big);
10 cout << " | ";
11 cout << small << " ";
12 binary(small);
13 cout << endl;
14 }
15 return 0;
16 }
17 void binary(char num)
18 {
19 char bitMask = 1 << 7;
20 for (int i = 0; i < 8; i++)
21 {
22 cout << (bitMask & num ? 1 : 0);
23 num = num << 1;
24 if(i == 3)
25 cout << ' ';
26 }
27 }我将大写字母的ASCII码和小写字母的ASCII转成二进制进行对比。


我们发现,大写字母的ASCII码二进制形式中,第六位都为0,相反小写字母的都为1。也就是说,我将第六位置1就是转成小写字母, 置0就是转成大写字母。置1需要用到按位或,置0需要用到按位与。
1 #include <iostream>
2 using namespace std;
3 void toupper(char & ch);
4 void tolower(char & ch);
5 int main()
6 {
7 char a = 'A';
8 cout << "first:" << a << endl;
9 toupper(a);
10 cout << "upper:" << a << endl;
11 tolower(a);
12 cout << "lower:" << a << endl << endl;
13 a = 'a';
14 cout << "first:" << a << endl;
15 toupper(a);
16 cout << "upper:" << a << endl;
17 tolower(a);
18 cout << "lower:" << a << endl;
19 return 0;
20 }
21 void toupper(char & ch)
22 {
23 ch = ch & 0XDF; //1101 1111
24 }
25 void tolower(char & ch)
26 {
27 ch = ch | 0X20;//0010 0000
28 }
大小写字母转换就这样完成了。
NOTE:对于初学者来说void toupper(char & ch);这种写法可能没见过。可以百度一下引用的相关知识。或者可以用指针来替代,甚至直接的值传递,把结果作为返回值。
相关推荐
fengjing81 2020-02-19
dxbjfu0 2020-01-24
一只懒虫 2019-06-29
yangkunlun 2019-06-28
jaminliu0 2019-06-28
chenmingwei 2009-08-28
PythonGCS 2018-07-09
PHP100 2019-03-28
DCXabc 2020-05-05
bnmcvzx 2020-05-03
zhglinux 2019-12-11
typhoonpython 2019-11-19
playis 2019-11-09
风火一回一生不毁 2014-05-29
独行者0 2019-10-31
88941536 2019-08-02
shlamp 2013-01-04