Convert C ++ to binary ASCII code in decimal format
Reference blog: <C ++> convert decimal number to binary display
Because the function I want to implement is limited to the char type, I wrote one according to the reference.
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 }
Running result:
For the sake of beauty, I added a space in the middle. Next we will discuss the case-sensitivity conversion of ASCII codes. programmers must know that the difference between uppercase and lowercase letters is fixed.
You only need to add (+) or subtract (-) 32 to convert the case. However, what should I do if I don't know whether to convert uppercase or lowercase letters?
See the following 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 }
I will convert the ASCII code of uppercase letters to the ASCII code of lowercase letters into binary for comparison.
We found that in the binary ASCII code of uppercase letters, the sixth digit is 0, and the opposite is 1 for lowercase letters. That is to say, I convert position 6 to lowercase letters, and 0 to uppercase letters. If the value is set to 1, the bitwise OR is used. If the value is set to 0, the bitwise AND are used.
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 111124 }25 void tolower(char & ch)26 {27 ch = ch | 0X20;//0010 000028 }
Converts uppercase and lowercase letters.
NOTE: For Beginners, void toupper (char & ch); this method may not have been seen. BaiduReference. Or you can use a pointer to replace or even directly pass the value and use the result as the return value.