转换思路
A| B …C
D
含义:A:目标进制 B:待转数值
C:余数 D:商
eg:10进制—>8进制
8| 100 …4
8| 12 …4
8| 1 …1
0
将余数倒序排列得到结果。
代码实现:
十进制 转 其他进制
//parameter: value:待转数值 baseSystem:目标进制
int Ten2Other(int value, int baseSystem = 10)
{
//十进制转其他进制(默认转为十进制)
if (baseSystem > 16 || baseSystem < 1)
{
return value;
}
int result = 0, index = 1;
while (value != 0)
{
result = (value % baseSystem)*index + result;
value /= baseSystem;
index *= 10;
}
return result;
}
其他进制 转 十进制
//parameter: value:待转数值 baseSystem:待转数值进制
int Other2Ten(int value, int baseSystem)
{
//其他进制转十进制
if (baseSystem > 16 || baseSystem < 1)
{
return value;
}
int result = 0, index = 1;
while (value != 0)
{
result = (value % 10)*index + result;
value /= 10;
index *= baseSystem;
}
return result;
}