Java代码实现二进制、十进制互相转换

话不多说,直接上代码,反正也是转载的,只是为了测试精度缺失的验证。

转载地址: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();
    }

测试无误,可直接使用。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值