import java.math.BigDecimal;
public class text {
// 定义数组长度
private static final int LEN = 64;
public static void paddingString(double n, StringBuilder sb, int len) {
if (len < 0) {
return;
}
if (n > 1) {
n = n - 1;
paddingString(n, sb, len);
} else if (n < 1) {
n *= 2;
}
if (n > 1) {
sb.append(1);
paddingString(n, sb, --len);
return;
} else if (n < 1) {
sb.append(0);
paddingString(n, sb, --len);
return;
} else {
sb.append(1);
return;
}
}
private static byte[] setBitArray(String s) {
byte[] arr = new byte[LEN];
int temp;
for (int i = LEN; i > 0; i--) {
temp = s.charAt(i - 1) - 48;
arr[i - 1] = (byte) temp;
}
return arr;
}
public static double binaryToDouble(byte[] s) {
BigDecimal two = new BigDecimal(2);
BigDecimal bigDecimal = new BigDecimal(0);
BigDecimal temp = BigDecimal.ONE;
BigDecimal temp1;
for (int i = 0; i < s.length; i++) {
temp = temp.divide(two);
if (s[i] > 0) {
int a = s[i];
temp1 = new BigDecimal(a);
bigDecimal = bigDecimal.add(temp.multiply(temp1));
}
}
return bigDecimal.doubleValue();
}
public static String doubleToBinary(double n) {
StringBuilder stringBuffer = new StringBuilder(LEN);
// 填充并得到二进制结果
paddingString(n, stringBuffer, LEN);
int len;
if ((len = stringBuffer.length()) > LEN + 1) {
return stringBuffer.toString().substring(0, LEN + 1);
} else {
return stringBuffer.toString().substring(0, len);
}
}
public static byte[] bytesAdd(byte[] a, byte[] b) {
byte[] arr = new byte[LEN];
for (int i = LEN - 1; i > 0; i--) {
arr[i] = (byte) (arr[i] + a[i] + b[i]);
if (arr[i] > 1) {
arr[i] -= 2;
arr[i - 1] = 1;
}
}
return arr;
}
public static void main(String[] args){
String s = doubleToBinary(.1); // 转成二进制字符串
//0.1转换成二进制字符串可以有限位数转换,位数小于64
//0.00011001100110011001100110011001100110011001100110011010010101001
byte[] bytes = setBitArray(s); // 转成二进制数组 (一)
double d = binaryToDouble(bytes); // 在转double, 反向验证结果的准确性
System.out.println("十进制: " + d);
System.out.println("========下面同理=========");
String s1 = doubleToBinary(.2);
//0.2在字符串转换时,64位无法容纳,所以到了64位的时候会停止,但是当转换后的bate[]进行转化的时候,会出现精度缺失的问题
//0.00110011001100110011001100110011001100110011001100110100101010010
byte[] bytes1 = setBitArray(s1); // (二)
double d1 = binaryToDouble(bytes1);
System.out.println("十进制: " + d1);
byte[] add = bytesAdd(bytes, bytes1); // 二进制数组累加 (三)
System.out.println("result: " + binaryToDouble(add)); // 将数组转换为小数
}
}