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