10进制与2进制,8进制,16进制的相互转换

理解了原理不管什么进制的都可以类似的转换,只是我在转换时最开始没注意到char 类型的 0 和1 其实对应的int类型的是48 和49

这个明白了一切转换很容易

10进制与2进制的相互转换

 

public static void main(String[] args) {
		int count = 2174;
		//to 2进制
		String str = "";
		while(true){
			str = count%2 + str;
			count = count/2;
			if(count<2){
				str = count%2 + str;
				break;
			}
		}
		System.out.println(str);
		
		String str1 = "100001111110";
		int count1 = 0;
		
		for(int i=str1.length()-1;i>=0;i--){
			int temp = 1;
			for(int j =0;j<str1.length()-i-1;j++){
				temp = temp*2;
			}
			//System.out.println(temp);
			if(str1.charAt(i) == '0'){
				count1 = count1+0;
			}else if(str1.charAt(i) == '1'){
				count1 = count1+temp;
			}
			}
		System.out.println(count1);
		
		System.out.println((int)'0');
	}


10进制与8进制的相互转换

 

 

public static void main(String[] args) {
		int count = 125350566;
		String str = "";
		// to 8进制
		while (true) {
			str = count % 8 + str;
			count = count / 8;
			if (count < 8) {
				str = count % 8 + str;
				break;
			}
		}
		System.out.println(str);

		String count8 = "736131246";
		int count10 = 0;

		for (int i = count8.length() - 1; i >= 0; i--) {
			int temp = 1;
			for (int j = 0; j < count8.length() - i - 1; j++) {
				temp = temp * 8;
			}
			count10 = count10 + temp * (count8.charAt(i) - 48);
		}
		System.out.println(count10);
	}


10进制与16进制的相互转换

 

 

public static void main(String[] args) {

		int count = 32311802;
		String str = "";
		char[] index = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
				'B', 'C', 'D', 'E', 'F' };
		while (true) {
			str = index[count % 16] + str;
			count = count / 16;
			if (count < 16) {
				if (count != 0)
					str = index[count % 16] + str;
				break;
			}
		}
		System.out.println(str);

		String str16 = "1ED09FA";
		int temp = 1;
		int count10 = 0;
		for (int i = str16.length() - 1; i >= 0; i--) {
			for (int j = 0; j < index.length; j++) {
				if (str16.charAt(i) == index[j]) {
					temp = j;
				}
			}
			int temp1 = 1;
			for (int j = 0; j < str16.length() - i - 1; j++) {
				temp1 = temp1 * 16;
			}
			count10 += temp * temp1;
		}
		System.out.println(count10);
	}



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值