java实现十进制小数转换二进制

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cds86333774/article/details/51211505

整数和小数分别转换.
整数除以2,商继续除以2,得到0为止,将余数逆序排列.

22 / 2      11  余 0
11 / 2      5   余 1
5  / 2      2   余 1
2  / 2      1   余 0
1  / 2      0   余 1

所以22的二进制是10110
小数乘以2,取整,小数部分继续乘以2,取整,得到小数部分0为止,将整数顺序排列.

0.8125x2=1.625  取整1,小数部分是0.625
0.625x2=1.25    取整1,小数部分是0.25
0.25x2=0.5      取整0,小数部分是0.5
0.5x2=1.0       取整1,小数部分是0,结束

所以0.8125的二进制是0.1101
十进制22.8125等于二进制10110.1101


代码

    public static String decimal2Binary(double value) throws Exception {
        // 整数部分的值
        int in = (int) value;
        System.out.println("The integer is: " + in);
        // 小数部分的值
        double r = value - in;
        System.out.println("The decimal number is: " + r);

        StringBuilder stringBuilder = new StringBuilder();
        // 将整数部分转化为二进制
        int remainder = 0;
        int quotient = 0;
        while (in != 0) {
            // 得商
            quotient = in / 2;
            // 得余数
            remainder = in % 2;
            stringBuilder.append(remainder);
            in = quotient;
        }
        stringBuilder.reverse();
        stringBuilder.append(".");

        // 将小数部分转化为二进制
        int count = 32; // 限制小数部分位数最多为32位,如果超过32为则抛出异常
        double num = 0;
        while (r > 0.0000000001) {
            count--;
            if (count == 0) {
                throw new Exception("Cannot change the decimal number to binary!");
            }
            num = r * 2;
            if (num >= 1) {
                stringBuilder.append(1);
                r = num - 1;
            } else {
                stringBuilder.append(0);
                r = num;
            }
        }

        return stringBuilder.toString();
    }

测试

    public static void main(String[] args) {
        try {
            String s = decimal2Binary(22.8125);
            System.out.println("The result is: " + s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

输出

The integer is: 22
The decimal number is: 0.8125
The result is: 10110.1101

猜你喜欢

转载自blog.csdn.net/cds86333774/article/details/51211505