進制轉換封裝庫
#include <iostream>
#include <string>
using namespace std;
/****************************************************************************
* 函數功能:字符串轉換爲數字 將任意2-36進製表示的字符串轉化爲十進制數。
* @param s對應進制的字符串,不含前綴如0x,0等
* radix 字符串是幾進製表示的
*
* @return 當前毫秒數
*****************************************************************************/
int AToI(string& s,const int& radix)
{
int ans = 0;
char t ='0';
for (size_t i=0;i<s.size();++i)
{
t = s[i];
if (t >= '0' && t <= '9')
{
ans = ans * radix + t - '0';
}
else
{
ans = ans * radix + t - 'a' + 10;
}
}
return ans;
}
/****************************************************************************
* 函數功能:數字轉換爲字符串 將十進制轉換爲對應的幾進製表示的字符串
* @param n 數字
* radix 幾進制
*
* @return 當前毫秒數
*****************************************************************************/
string IToA(int n, int radix)
{
string ans = "";
int t = 0;
do {
t = n % radix;
if (t >= 0 && t <= 9)
{
ans += t + '0';
}
else
{
ans += t - 10 + 'a';
}
n /= radix;
} while (n != 0);
reverse(ans.begin(), ans.end());
return ans;
}
int main()
{
cout << IToA(32, 16) << endl;
string s = "42";
cout << AToI(s,16) << endl;
getchar();
return 0;
}