a进制转b进制
思想:a进制转十进制 十进制转b进制
a进制转十进制
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
const int p=16;//p代表 a进制
int main()
{
long long n=0,fal=1;
string s;
cin>>s;
for(int i=0;i<s.size();i++)
{
if(s[i]=='-') fal=-1;
else if(s[i]>'9') n=n*p+s[i]-55;
else n=n*p+s[i]-'0';
}
cout<<n*fal<<endl;
return 0;
}
十进制转b进制
#include<iostream>
#include<stack>
using namespace std;
const int p=16;//p代表 b进制
stack<int> s;
int tmp;
void swit(int n)
{
if(n==0) s.push(0);
while (n!=0)
{
tmp=n%p;
n=n/p;
s.push(tmp);
}
}
int main()
{
int n;
cin>>n;
swit(n);
while(!s.empty())
{
if(s.top()>=10) cout<<(char)(s.top()+55);
else cout<<s.top();</span>
s.pop();
}
return 0;
}
通过库函数实现八进制、十六进制输出:
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int main()
{
int test=64;
//十进制 DEC
cout<<test<<endl;
//八进制 OCT
cout<<oct<<test<<endl;
printf("%o\n",test);
//十六进制 HEX
cout<<hex<<test<<endl;
printf("%x\n",test);
//printf("%b\n",test);
return 0;
}
十进制转二进制:
#include<iostream>
using namespace std;
void swit(int n)
{
for(int i=16,fal=0;i>=0;i--)
if(n&(1 << i)) cout << "1",fal=1;
else if(fal) cout << "0";
}
int main()
{
swit(8);
return 0;
}