二进制转化为十进制Java实现

  • 二进制转化为十进制
    ①按权展开方法Java实现
/*
	 * 按权展开法
	 */
	public static double BinToTen1(String binary) {
		//查找该二进制是否存在小数点
		int index = binary.indexOf('.');
		//转化成的十进制
		double ten = 0;
		//整数部分
		double integer = 0;
		//小数部分
		double decimal = 0;
		//index等于-1,说明没有小数部分
		if(index == -1) {
			for(int i = 0; i < binary.length(); i++) {
				//48为字符'0'对应的ASCII值;
				//ten += (binary.charAt(i) - 48) * Math.pow(2, -(i-(binary.length() - 1)));
				//或者可以将字符转化为字符串,再由字符串转化为数字
				ten += Integer.parseInt(String.valueOf(binary.charAt(i))) * Math.pow(2, -(i-(binary.length() - 1)));
			}
		} else {
			//计算整数部分
			for(int i = 0; i < index; i++) {
				integer += Integer.parseInt(String.valueOf(binary.charAt(i))) * Math.pow(2, -(i-(index - 1)));
			}
			//计算小数部分
			for(int j = index + 1; j < binary.length(); j++) {
				decimal += Integer.parseInt(String.valueOf(binary.charAt(j))) * Math.pow(2, (index - j));
			}
			ten = integer + decimal;
		}
		return ten;
		
	}

测试

public static void main(String[] args) {
		
		double a = BinToTen1("11");
		System.out.println(a);
		double b = BinToTen1("0.11");
		System.out.println(b);
		double c = BinToTen1("11.111");
		System.out.println(c);
	}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_37711738/article/details/89531816