Reference blog:<c++> decimal number conversion to binary display
Since the function I want to implement is limited to the char type, I wrote one based on the reference.
1#include <iostream>2 using namespacestd;3 voidBinaryCharnum);4 intMain ()5 {6Binary'a');7 return 0;8 }9 voidBinaryCharnum)Ten { One CharBitmask =1<<7; A for(inti =0; I <8; i++) - { -cout << (bitmask & num?)1:0); thenum = num <<1; - if(i = =3) -cout <<' '; - } +}
Operation Result:
For the sake of beauty, I added a space in the middle. Next we discuss the ASCII code case conversion problem, presumably programming beginners know that the difference between the uppercase and lowercase letters of the value is fixed.
Uppercase and lowercase conversions only need to add (+) or minus (-) 32 on the line. But what if I don't know if the letters you want to convert are uppercase or lowercase?
Take a look at the following code:
1#include <iostream>2 using namespacestd;3 voidBinaryCharnum);4 intMain ()5 {6 for(CharBig ='A', small ='a'; Small <='Z'; big++, small++)7 {8cout << Big <<" ";9 binary (big);Tencout <<" | "; Onecout << Small <<" "; A binary (small); -cout <<Endl; - } the return 0; - } - voidBinaryCharnum) - { + CharBitmask =1<<7; - for(inti =0; I <8; i++) + { Acout << (bitmask & num?)1:0); atnum = num <<1; - if(i = =3) -cout <<' '; - } -}
I compare the ASCII of capital letters to the ASCII of lowercase letters into binary.
We found that in the ASCII binary form of uppercase letters, the sixth bit was 0, whereas the lowercase letters were 1. That is, I will place the sixth position 1 is to turn into lowercase letters, 0 is to turn into uppercase letters. 1 need to use a bitwise OR, 0 need to use the bitwise AND.
1#include <iostream>2 using namespacestd;3 voidToUpperChar&ch);4 voidToLowerChar&ch);5 intMain ()6 {7 CharA ='A';8cout <<"First :"<< a <<Endl;9 ToUpper (a);Tencout <<"Upper:"<< a <<Endl; One ToLower (a); Acout <<"Lower:"<< a << Endl <<Endl; -A ='a'; -cout <<"First :"<< a <<Endl; the ToUpper (a); -cout <<"Upper:"<< a <<Endl; - ToLower (a); -cout <<"Lower:"<< a <<Endl; + return 0; - } + voidToUpperChar&ch) A { atCH = ch &0XDF;//1101 1111 - } - voidToLowerChar&ch) - { -CH = ch |0X20;//0010 0000 -}
The uppercase and lowercase letters conversion is done.
Note: void ToUpper (char & CH) for beginners, this may not be seen. Can Baidu a reference to the relevant knowledge. Alternatively, you can use pointers instead of even direct values to pass the result as a return value.
C + + decimal-to-binary ASCII code-case conversion