今天我就来发一下c++进制转换的源代码
1、二进制转十进制模板
#include<iostream>
#include<math.h>
using namespace std;
unsigned long long d;
int ttt(unsigned long long n,unsigned long long num=0){//tow to ten
cout<<"输入一个二进制数:";
cin>>n;
cout<<n<<"的十进制数是:";
for(unsigned long long i=0;n!=0;++i){
d=n%10;
num=(d)*(pow(2,i))+num;
n=n/10;
}
return num;
}
int main(){
return 0;
}
2、十进制转二进制模板
#include<iostream>
using namespace std;
int main(){
using i=int;
i de;
i bin;
i k=1,j=0;
cin>>de;
while(de!=0){
bin=de%2;
de=de/2;
j=j+k*bin;
k=k*10;
}
cout<<j;
}
3、十进制转十六进制模板
#include<iostream>
#include<stack>
using namespace std;
int main(){
long long n;
int base=16;
cin>>n;
stack<char>S;
char a[]="0123456789ABCDEF";
if(n==0){
S.push(a[0]);
}
while(n>0){
S.push(a[n%base]);
n/=base;
}
while(!S.empty()){
cout<<S.top();
S.pop();
}
}
4、十六进制转八进制模板
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i,j,k;
int n;
string s1;
string s2;
cin>>n;
for(i=0;i<n;i++){
cin>>s1;
s2="";
for(j=0;j<s1.length();j++){
switch (s1[j]){
case '0':s2+="0000";break;
case '1':s2+="0001";break;
case '2':s2+="0010";break;
case '3':s2+="0011";break;
case '4':s2+="0100";break;
case '5':s2+="0101";break;
case '6':s2+="0110";break;
case '7':s2+="0111";break;
case '8':s2+="1000";break;
case '9':s2+="1001";break;
case 'A':s2+="1010";break;
case 'B':s2+="1011";break;
case 'C':s2+="1100";break;
case 'D':s2+="1101";break;
case 'E':s2+="1110";break;
case 'F':s2+="1111";break;
default:break;
}
}
if(s2.length()%3==1){
s2="00"+s2;
}
if(s2.length()%3==2){
s2="0"+s2;
}
int flag=0;
for(k=0;k<s2.length()-2;k+=3){
int output=4*(s2[k]-'0')+2*(s2[k+1]-'0')+s2[k+2]-'0';
if(output){
flag=1;
}
if(flag){
cout<<output;
}
}
cout<<endl;
}
return 0;
}
5、十六进制转十进制模板
#include <iostream>
#include <string>
using namespace std;
int main(){
string s1,s2;
int i,j;
long long sum=0;
s2="";
cin>>s1;
for(i=0;i<s1.length();i++){
switch(s1[i]){
case '0':s2+="0000";break;
case '1':s2+="0001";break;
case '2':s2+="0010";break;
case '3':s2+="0011";break;
case '4':s2+="0100";break;
case '5':s2+="0101";break;
case '6':s2+="0110";break;
case '7':s2+="0111";break;
case '8':s2+="1000";break;
case '9':s2+="1001";break;
case 'A':s2+="1010";break;
case 'B':s2+="1011";break;
case 'C':s2+="1100";break;
case 'D':s2+="1101";break;
case 'E':s2+="1110";break;
case 'F':s2+="1111";break;
default:break;
}
}
for(j=0;j<s2.length();j++){
sum=sum*2+s2[j]-'0';
}
cout<<sum;
return 0;
}