首页 > 技术文章 > JAVA:二进制和十进制互转

leonlipfsj 2019-12-23 21:19 原文

package com.xxx.transfer;

/**
 * 数字进制相互转换
 * @see JDK中提供了这些功能
 * @author le.li
 *
 */
public class NumberUtil {
    public static void main(String[] args) {
        // 通过X的n次方相加的方式,将二进制转换成十进制
        System.out.println(binary2Decimal("1001"));
        // 通过取余数的方式,将十进制转成二进制
        System.out.println(decimal2Binary(9));
        
        // jdk中二进制转十进制方式
        System.out.println(Integer.parseInt("1001", 2));
        // jdk中十进制转二进制方式
        System.out.println(Integer.toBinaryString(9));
        System.out.println(Integer.toString(9, 2));
    }
    
    /**
     * 二进制转十进制
     * @param number
     * @return
     */
    public static int binary2Decimal(String number) {
        return scale2Decimal(number, 2);
    }
    
    /**
     * 其他进制转十进制
     * @param number
     * @return
     */
    public static int scale2Decimal(String number, int scale) {
        checkNumber(number);
        if (2 > scale || scale > 32) {
            throw new IllegalArgumentException("scale is not in range");
        }
        // 不同其他进制转十进制,修改这里即可
        int total = 0;
        String[] ch = number.split("");
        int chLength = ch.length;
        for (int i = 0; i < chLength; i++) {
            total += Integer.valueOf(ch[i]) * Math.pow(scale, chLength - 1 - i);
        }
        return total;
        
    }
    
    /**
     * 二进制转十进制
     * @param number
     * @return
     */
    public static String decimal2Binary(int number) {
        return decimal2Scale(number, 2);
    }
    
    /**
     * 十进制转其他进制
     * @param number
     * @param scale
     * @return
     */
    public static String decimal2Scale(int number, int scale) {
        if (2 > scale || scale > 32) {
            throw new IllegalArgumentException("scale is not in range");
        }
        String result = "";
        while (0 != number) {
            result = number % scale + result;
            number = number / scale;
        }
        
        return result;
    }
    
    public static void checkNumber(String number) {
        String regexp = "^\\d+$";
        if (null == number || !number.matches(regexp)) {
            throw new IllegalArgumentException("input is not a number");
        }
    }
}

 

推荐阅读