public static void main(String[] args) {
// int res1 = toTen("1730f", 16);
// System.out.println(res1);
ten2X(2349, 16);
}
/**
* 将10进制数转化为其他进制比如2,,8,16;
* @param digit 待转的具体数字;
* @param x 转化为其他进制比如2,,8,16;
*/
public static void ten2X(int digit, int x) {
StringBuffer sb = new StringBuffer();
for (int i = digit; i > 0; i /= x) {
int res = i % x;
if (x == 16 && res > 9) {
char s = (char) ('A' + res - 10);
sb.insert(0, s);
} else {
sb.insert(0, res);
}
}
System.out.println(sb);
}
/**
* 将字符串转换成10进制
*
* @param str
* 待转换的数字型字符串
* @param x
* 具体进制,比如2,8,16
* @return 转换成的10进制数字
*/
public static int xtoTen(String str, int x) {
int len = str.length();
int sum = 0;
for (int i = 0; i < len; i++) {
char c = str.charAt(len - i - 1);
int n = Character.digit(c, x);
switch (x) {
case 2:
sum += n * (1 << i);
break;
case 8:
sum += n * (1 << (3 * i));
break;
case 16:
sum += n * (1 << (4 * i));
break;
}
}
return sum;
}