进制转换(任意进制转换)

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;
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值