首页 > 其他 > 详细

二进制转10进制

时间:2019-08-18 17:05:23      阅读:87      评论:0      收藏:0      [点我收藏+]
public class BB {
    public static void main(String[] args) throws Exception {
        System.out.println(parseInt("11100000000000000000000000000000",2));
        System.out.println(parseInt("11100000000000000000000000000001",2));
        System.out.println(parseInt("11100000000000000000000000000011",2));
        System.out.println(parseInt("01111111111111111111111111111111",2));
    }
    
    public static int parseInt(String s, int radix) throws Exception {

        int result = 0;
        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < 0) { // Possible leading "+" or "-"
                if (firstChar == -) {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != +)
                    throw new Exception(s);

                if (len == 1) // Cannot have lone "+" or "-"
                    throw new Exception(s);
                i++;
            }
            multmin = limit / 1;
            while (i < len) {
                digit = Character.digit(s.charAt(i++), radix);
                if (digit < 0) {
                    throw new Exception(s);
                }
                if (result < multmin) {
                    throw new Exception(s);
                }
                result *= radix;
                result -= digit;
            }
        } else {
            throw new Exception(s);
        }
        return negative ? result : -result;
    }
}

 

二进制转10进制

原文:https://www.cnblogs.com/yaowen/p/11372840.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!