1. Java
利用两个库方法即可:
1. Integer方法
public static String toString(int i, int radix)
将目标数据i 转换成radix进制的字符
2. Integer.parseInt(String str,int radix)
将目标字符串转换成radix进制的整型数据
Java进制转换;
package integerDemo;
import java.util.Scanner;
public class integerDemo
{
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("输入待转换数据:");
String str = input.next();
System.out.println("待转换数据进制:");
int hexM = input.nextInt();
System.out.println("目标进制:");
int hexN = input.nextInt();
if (hexM > 36 || hexM < 2 || hexN > 36 || hexN < 2)
throw new Exception("wrong para,2=<m,n>=36");
hexTo(str, hexM, hexN);
}
public static void hexTo(String str, int hexM, int hexN)
{
System.out.println(Integer.toString(Integer.parseInt(str, hexM), hexN));
}
}
2. C
先用乘法换成十进制数,然后辗转相除获取转换进制数(有限制,不能超出整型最大取值范围)
#include <stdio.h>
#include <string.h>
#define M 100
#define N 200
void main()
{
void mToN(int m, char* strM, int n, char* strN);
char strM[M], strN[N];
int m,n;
gets(strM);//输入
scanf("%d %d",&m,&n);
//可以加上对参数的约束
mToN(m,strM,n,strN);
puts(strN);//输出
}
void mToN(int m, char* strM, int n, char* strN)
{
int i = 0;
char c, *p = strN;
//乘法获取10进制数
while (*strM != '\0')
i = i*m + *strM++ - '0';
//辗转取余
while (i) {
*p++ = i % n + '0';
i /= n;
}
*p-- = '\0';//加上结尾标识,p指向最后一个字符
//逆置余数序列或者逆向输出也可以
while (p > strN) {
c = *p;
*p-- = *strN;
*strN++= c;
}
}