最近有个项目用到各种进制之间的转换,比如10进制转40进制,转二进制等。
于是写了一个简单的共通进制转换函数。
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
//任意进制转换函数
//oldNum为转换前的数字,oldHex则是转换前的进制
//newNum为转换后的数字,newHex则是转换后的进制
bool HexChange( vector<int> oldNum, int oldHex, vector<int>& newNum, int newHex)
{
if(oldNum.size() < 1 || oldHex < 2 || newHex < 2)
return false;
newNum.clear();
bool HexTest = true;
while(HexTest)
{
HexTest = false;
int remainder = 0;//每位的余数
for(size_t i = 0; i<oldNum.size();++i)
{
int tempNum = (remainder * oldHex + oldNum[i]) / newHex;
remainder = (remainder*oldHex + oldNum[i]) % newHex;
if(tempNum != oldNum[i])//整个oldNum会逐渐变小,直到不再改变
{
oldNum[i] = tempNum;
HexTest = true;
}
}
if(HexTest)
{
newNum.push_back(remainder);
remainder = 0;
}
}
reverse(newNum.begin(),newNum.end());//倒转
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
//十进制:5459
vector<int> oldNum;
oldNum.push_back(7);
oldNum.push_back(4);
oldNum.push_back(5);
oldNum.push_back(9);
vector<int> newNum;
//转16进制得到:1,13,2,3
if(HexChange(oldNum,10,newNum,16))
{
for(size_t i = 0; i < newNum.size(); ++i)
cout<<newNum[i]<<",";
}
//转2进制得到:1110100100011
if(HexChange(oldNum,10,newNum,2))
{
cout<<endl;
for(size_t i = 0; i < newNum.size(); ++i)
cout<<newNum[i];
}
return 0;
}