话不多说,直接上代码,反正也是转载的,只是为了测试精度缺失的验证。
转载地址:https://blog.csdn.net/weixin_37610397/article/details/79928221
https://blog.csdn.net/u014102846/article/details/75394186
二进制转换为十进制:
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(".");
total.append(doubleToBinary(d));
return total;
}
public static StringBuilder doubleToBinary(double d) throws Exception {
return doubleToBinary(d, 25);//利用方法重装实现默认参数
}
public static StringBuilder doubleToBinary(double d, int count) throws Exception {
if (count > 32) {
throw new Exception("The max bit must less than 32!");
}
if (count == 0) {
throw new Exception("The min bit must bigger than 0");
}
double multi = 0; //每次的乘积
StringBuilder res = new StringBuilder();
while (count >= 0) {
multi = d * 2;
if (multi >= 1) {
res.append(1);
d = multi - 1;
} else {
res.append(0);
d = multi;
}
count--;
}
return res;
}
public static StringBuilder intToBinary(int in) throws Exception {
StringBuilder binary = new StringBuilder();
while (in != 0) {
int quotient = in / 2; //商
int remender = in % 2; //余数
binary.append(remender);
in = quotient;
}
return binary.reverse();
}
测试无误,可直接使用。