进制转换(二进制转16进制)

Problem Description

把二进制数转化为十六进制数。

Input

多组测试数据。
每组数据一行,由0和1组成,表示一个二进制的数。
已知输入长度不超过1000000,没有前导0。

Output

转化成对应的十六进制数输出。

Sample Input

10
11111
11101110

Sample Output

2
1F
EE
用栈很好做代码如下:
# include <iostream>
# include <numeric>
# include <algorithm>
# include <functional>
# include <list>
# include <map>
# include <set>
# include <stack>
# include <deque>
# include <queue>
# include <vector>
# include <ctime>
# include <cstdlib>
# include <cmath>
# include <string>
# include <cstring>


using namespace std;


const int maxx = 1000005;
int a[maxx] = {0};
int main(int argc, char *argv[])
{


	char s[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};


//	cout << pow(2, 0) << endl;
	string str;
	while(cin >> str)
	{


		memset(a, 0, sizeof(a));
		int k = str.size() % 4;
		int l;
		int j;
		if(k == 0)
		{
			l = str.size();
			j = 0;
		}
		else
		{
			l = str.size() + 4 - k;
			j = 4 - k;
		}
	//	cout << "l = " << l << " ,k = " << k << endl;






		for(int i = 0; i < str.size(); i++, j++)
		{
			a[j] = str[i] - '0';
	//		cout << "j = " << j << " ," << a[j] << endl;
		}
	//	for(int i = 0; i < l; i++)
	//	{
	//		cout << "a[" << i << "] = " << a[i] << endl;
	//	}
		int f = 0;
		int t = 0;
		stack<char> ss;
		for(int i = l - 1; i >= 0; i--)
		{
			if(a[i])
			{
				t = t + pow(2, f);
		//		cout << "ttt = " << t << ",i = " << i << endl;
			}
			f++;
			if(f == 4)
			{
		//		cout << "t = " << t << ",i = " << i << ",s[t] = " << s[t] << endl;
				ss.push(s[t]);
				t = 0;
				f = 0;
			//	cout << "t = " << t << ",f = " << f << endl;
			}
		}
		while(!ss.empty())
		{
			cout << ss.top();
			ss.pop();
		}
		cout << endl;


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值