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"); } } }
