任意进制转换

首先我们来看一个简单的十进制转换到二进制的题目。

Description:

将十进制整数转换成二进制数。

 Input:

输入数据中含有不多于50个整数n。

Output:

对于每个n,以11位的宽度右对齐输出n值,然后输出“-->”,再然后输出二进制数。每个整数n的输出,独立占一行。

Sample Input:

	2
	0
	-12
	1

Sample Output:

          2-->10
          0-->0
        -12-->-1100
          1-->1
代码如下:
#include<iostream>
#include<fstream>
#include<vector>
#include<string>
#include<iterator>
#include<algorithm>
#include<functional>
#include<iomanip>
using namespace std;
int main()
{
    ifstream cin("D:\\data.txt");
    int n(0);
    string str;
    while (cin >> n)
    {
        if (0 == n)
        {
            cout << setw(11) << n << "-->" << 0 << endl;
            continue;
        }
        str = "";
        for (int a = n; a!=0; a /= 2)
        {
            str = str + (a % 2 ? '1': '0');
        }
        std::reverse(str.begin(), str.end());
        cout << setw(11) << n << (n>0?"-->":"-->-") << str << endl;
    }
    system("pause");
    return 0;
}
下面的程序则可以实现做任意进制的转换:
#include<iostream>
#include<fstream>
#include<vector>
#include<string>
#include<iterator>
#include<algorithm>
#include<functional>
#include<iomanip>
using namespace std;
bool conversion(string& src, string& dst, long d1, long d2);
int main()
{
    string src,dst;
    long a(0), b(0);
    int n(0);
    while (cin >> src>>a>>b)
    {
        conversion(src, dst, a, b);
        cout << dst << endl;
    }
    system("pause");
    return 0;
}
//src为待转换进制的数字,dst为进制转换完成后的数字,二者均以字符串表示
//d1为原始的进制数,d2为要转换成的进制数
bool conversion(string& src, string& dst, long d1, long d2)
{
    dst = "";
    long num(0),t(0);
    char c;
    for (int i = 0; i < src.length(); i++)
    {
        if (src[i] >= '0' && src[i] <= '9')
        {
            t = src[i] - '0';
        }
        else
        {
            t = src[i] - 'A' + 10;
        }
        num = num*d1 + t;
    }
    int i(0);
    while (num)
    {
        t=num%d2;
        num =num/d2;
        if (t >= 0 && t <= 9)
            c = t + '0';
        else
            c = t + 'A' - 10;
        dst = dst + c;
        i++;
    }
    std::reverse(dst.begin(), dst.end());
    return true;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值