Number Systems Conversions using recursion
// Convert Decimal to Binary
public static int D2B(int n) {
if (n == 0) {
return 0;
}
return D2B(n / 2) * 10 + (n % 2);
}
-----------------------------------------------+
// Convert Binary to Decimal
public static int B2D(int b) {
if (b == 0) {
return 0;
}
return (b % 10) + 2 * B2D(b / 10);
}
-------------------------------------------------
// Convert Decimal to Octal
public static int D2O(int n) {
if (n == 0) {
return 0;
}
return D2O(n / 8) * 10 + (n % 8);
}
-------------------------------------------------
// Convert Octal to Decimal
public static int O2D(int o) {
if (o == 0) {
return 0;
}
return (o % 10) + 8 * O2D(o / 10);
}
-------------------------------------------------
// Convert Decimal to Hexadecimal (returns a String)
public static String D2H(int n) {
if (n == 0) {
return "";
}
String hexDigits = "0123456789ABCDEF";
return D2H(n / 16) + hexDigits.charAt(n % 16);
}
-------------------------------------------------
// Convert Hexadecimal to Decimal
public static int H2D(String h) {
if (h.length() == 0) {
return 0;
}
char firstChar = h.charAt(0);
int firstDigit = (firstChar >= '0' && firstChar <= '9') ? (firstChar - '0') : (firstChar - 'A' + 10);
return firstDigit * (int) Math.pow(16, h.length() - 1) + H2D(h.substring(1));
}
// Convert Decimal to Binary
public static int D2B(int n) {
if (n == 0) {
return 0;
}
return D2B(n / 2) * 10 + (n % 2);
}
-----------------------------------------------+
// Convert Binary to Decimal
public static int B2D(int b) {
if (b == 0) {
return 0;
}
return (b % 10) + 2 * B2D(b / 10);
}
-------------------------------------------------
// Convert Decimal to Octal
public static int D2O(int n) {
if (n == 0) {
return 0;
}
return D2O(n / 8) * 10 + (n % 8);
}
-------------------------------------------------
// Convert Octal to Decimal
public static int O2D(int o) {
if (o == 0) {
return 0;
}
return (o % 10) + 8 * O2D(o / 10);
}
-------------------------------------------------
// Convert Decimal to Hexadecimal (returns a String)
public static String D2H(int n) {
if (n == 0) {
return "";
}
String hexDigits = "0123456789ABCDEF";
return D2H(n / 16) + hexDigits.charAt(n % 16);
}
-------------------------------------------------
// Convert Hexadecimal to Decimal
public static int H2D(String h) {
if (h.length() == 0) {
return 0;
}
char firstChar = h.charAt(0);
int firstDigit = (firstChar >= '0' && firstChar <= '9') ? (firstChar - '0') : (firstChar - 'A' + 10);
return firstDigit * (int) Math.pow(16, h.length() - 1) + H2D(h.substring(1));
}