import java.util.regex.Pattern; public class NumberConvert { public static final Pattern bPattern = Pattern.compile("^[01]+$"); public static final Pattern oPattern = Pattern.compile("^[0-8]+$"); public static final Pattern hPattern = Pattern.compile("^[//dA-F]+$"); public static final char[] hexChars = { 'A', 'B', 'C', 'D', 'E', 'F' }; public static String toBinary(int value) { return NumberConvert.toOther(value, 2); } public static int fromBinary(String strInt) { if (!bPattern.matcher(strInt).find()) { throw new NumberFormatException("binary:" + strInt); } return NumberConvert.fromOther(strInt, 2); } public static String toOctal(int value) { return NumberConvert.toOther(value, 8); } public static int fromOctal(String strInt) { if (!oPattern.matcher(strInt).find()) { throw new NumberFormatException("octal:" + strInt); } return NumberConvert.fromOther(strInt, 8); } public static String toHex(int value) { return NumberConvert.toOther(value, 16); } public static int fromHex(String strInt) { strInt = strInt.toUpperCase(); if (!hPattern.matcher(strInt).find()) { throw new NumberFormatException("hex:" + strInt); } return NumberConvert.fromOther(strInt, 16); } private static int fromOther(String strInt, int base) { int pow = 0; int intVal = 0; for (int i = strInt.length() - 1; i >= 0; i--) { char ch = strInt.charAt(i); if (ch != '0') { if (ch > '0' && ch <= '9') { intVal += (ch - 48) * Math.pow(base, pow); } else if (ch >= 'A' && ch <= 'F') { intVal += (ch - 'A' + 10) * Math.pow(base, pow); } } pow++; } return intVal; } private static String toOther(int vint, int base) { int modval = 0; String str = ""; while (vint > 0) { modval = vint % base; vint = (int) Math.floor(vint / base); if (modval < 10) str = modval + str; else str = hexChars[modval - 10] + str; } return str; } public static void main(String args[]) { System.out.println(NumberConvert.toBinary(231)); System.out.println(NumberConvert.toOctal(231)); System.out.println(NumberConvert.toHex(231)); System.out.println(NumberConvert.fromBinary("11100111")); System.out.println(NumberConvert.fromOctal("347")); System.out.println(NumberConvert.fromHex("E7")); } }