将一个十进制数字转化为x进制/将x进制的字符串转换成10进制

<span style="font-size:18px;">public class JinZhiZhuanHuan {
	public static void main(String[] args) {

		// int res1 = toTen("1730f", 16);
		// System.out.println(res1);

		ten2X(2349, 8);

	}

	/**
	 * 将一个十进制数字转化为x进制
	 * @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);
	}

	/**
	 * 将x进制的字符串转换成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;
	}

}
</span>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值