话不多说,直接上代码,反正也是转载的,只是为了测试精度缺失的验证。
二进制转换为十进制:
public static double bin2DecXiao(String binXStr) {
double decX = 0.0; //位数
int k = 0;
for (int i = 0; i < binXStr.length(); i++) {
int exp = binXStr.charAt(i) - '0';
exp = -(i + 1) * exp;
if (exp != 0) {
decX += Math.pow(2, exp);
}
}
System.out.println("二进制小数为;" + binXStr + "。\r\n其对应的十进制为:" + decX);
return decX;
}
十进制转换为二进制:
public static StringBuilder allToBinary(double deci) throws Exception {
int in = (int) deci; //取整数部分
double d = deci - in; //小数部分
StringBuilder total = new StringBuilder();
total.append(intToBinary(in));
total.append(".");