C/C++教程

c++实现十进制转二进制、八进制、十六进制

本文主要是介绍c++实现十进制转二进制、八进制、十六进制,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#include<iostream>
#include<iomanip>
using namespace std;
int two(int n)
{
	int sum = 0, m = n,i=1,t=n;
	while (1)
	{
		if (t % 2 == 0)			//在该数能被8整除时尾数0用被整除次数补上0
		{
			i=i*10;
			t = t / 2;
		}
		else
		{
			break;
		}

	}
	
	
	while (n != 0)
	{
		sum = sum * 10 + n % 2;
		n = n / 2;
		
	}
	
	n = sum;
	sum = 0;
	while (n != 0)
	{
		sum = sum * 10 + n % 10;
		n = n / 10;

	}
	
	if (m % 2 == 0) return sum * i;
	else   return sum;
}

int eight(int n)
{
	int sum = 0, m = n, i = 1, t = n;
	while (1)
	{
		if (t % 8 == 0)			//在该数能被8整除时尾数0用被整除次数补上0
		{
			i = i * 10;
			t = t / 8;
		}
		else
		{
			break;
		}

	}


	while (n != 0)
	{
		sum = sum * 10 + n % 8;
		n = n / 8;

	}

	n = sum;
	sum = 0;
	while (n != 0)
	{
		sum = sum * 10 + n % 10;
		n = n / 10;

	}

	if (m % 8 == 0) return sum * i;
	else   return sum;
}

void six(int n)
{
	int i, j;
	string  arr[100];
	int m;
	string al[16] = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
	for ( i = 0;n>0; i++)
	{
		arr[i] = al[n % 16];
		n = n / 16;
		m = i;
	}
	for (j = m; j >= 0; j--)
	{
	  cout << arr[j] ;
	}
}

int main()
{
	int n,m;
	cin >> n>>m;

	switch (m)
	{
	case 2:cout << two(n) << endl; break;
	case 8:cout << eight(n) << endl; break;
	case 16: six(n); break;
	}
	
	return 0;
}

这篇关于c++实现十进制转二进制、八进制、十六进制的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!