编程实现把十进制数(long型)分别以二进制和十六进制形式输出

/*
	编程实现把十进制数(long型)分别以二进制和十六进制形式输出,不能使用printf系列。
//*/

// 使用移位操作,二进制可以左移,16进制采用右移

#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

template <class T>
void swap_t(T &lp, T &rp){
	T tmp = lp;
	lp = rp;
	rp = tmp;
}


template <class T>
void reverse(T data[], int begin, int end)
{
	while(begin < end){
		swap_t(data[begin], data[end]);
		++begin;
		--end;
	}
}
/*
int main(int argc, char** argv)
{
	if(argc < 2)
		return -1;
	char Href[17] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','\0'};
	char Binref[] = "0000000100100011010001010110011110001001101010111100110111101111";
	int val = atoi(argv[1]);
	char hex[50];
	char bin[50];
	int i = 0;
	while(val > 16){
		hex[i] = Href[val%16];
		i += 1;
		val /= 16;
	}
	hex[i] = Href[val];
	hex[i+1] = '\0';
	reverse(hex, 0, i);
	cout << "十六进制输出: \t" <<"0X" << hex << endl;
	int k = 0;
	for(int j = 0; j <= i; ++j){
			if(hex[j] <= '9'){
				for(k = 4*j; k < 4*(j+1); ++k){
				bin[k] = Binref[(hex[j] - '0') * 4 + k - j*4];   // 按十六进制编码索引二进制编码
				}
			}else{
				for(k = 4*j; k < 4*(j+1); ++k){
				bin[k] = Binref[(hex[j] - 'A' + 10) * 4 + k - j*4];
				}
			}		
	}
	bin[k] = '\0';
	cout << "二进制输出: \t" << bin << endl;

	return 0;
}
//*/
int main(int argc, char** argv)
{
	if(argc < 2)
		return -1;
	char Href[17] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','\0'};
	//char Binref[] = "0000000100100011010001010110011110001001101010111100110111101111";
	int val = atoi(argv[1]);
	
	int bref = 1;
	bool barr[50];
	int idx = 0;
	while(val > 0){
		if(val & 1){
			barr[idx] = 1;
			++idx;
			val = val >> 1;
		}else{
			barr[idx] = 0;
			++idx;
			val = val >> 1;
		}
	}
	int zeros = 0;
	if(idx%4 != 0){ 
		zeros = 4 - idx%4;
		for(int zr = 0; zr < zeros; ++zr){
			barr[idx+zr] = 0;
		}
	}
	idx = idx + zeros;
	reverse(barr, 0, idx -1);
	for(int i = 0; i < idx; ++i)
		cout << barr[i];

	cout << endl;

	int val16 = 0;
	if(idx%8){
		cout <<"0x0";
	}else{
		cout <<"0x";
	}
	for(int i = 0; i < idx; i = i+4){
		val16 = barr[i] * 8 + barr[i+1] * 4 + barr[i+2] * 2 + barr[i+3];
		cout << Href[val16];
	}
	cout << endl;



	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值