C++ 十進制轉二進制 ASCII碼大小寫轉換

參考博客:<C++>十進制數轉換成二進制顯示ios

 

因爲我要實現的功能侷限於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 }

運行結果如圖:spa

爲了美觀,我在中間加了一個空格。接下來討論ASCII碼大小寫轉換的問題了,想必編程初學者都知道大寫字母和小寫字母之間相差的值是固定的。.net

大小寫轉換隻須要加(+)或減(-)32就好了。可是,遇到不知道須要轉換的字母是大寫仍是小寫該怎麼辦?指針

請看以下代碼:code

 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轉成二進制進行對比。blog

咱們發現,大寫字母的ASCII碼二進制形式中,第六位都爲0,相反小寫字母的都爲1。也就是說,我將第六位置1就是轉成小寫字母, 置0就是轉成大寫字母。置1須要用到按位或,置0須要用到按位與。get

 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);這種寫法可能沒見過。能夠百度一下引用的相關知識。或者能夠用指針來替代,甚至直接的值傳遞,把結果做爲返回值。it

相關文章
相關標籤/搜索