Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

In this tutorial, we'll explore how to convert a number from one base to another in Java. There would be two approaches used in converting a number from, let's say, base 2 to base 5 and vice versa.

2. The Integer class

The java.lang package has the Integer class, a wrapper class, that wraps a primitive type int to an Integer object. This class has several methods for manipulating an int and for converting an int to a String object and a String to an int type. The parseInt() and toString() methods would be needed to help us convert numbers from one base to another.

2.1. parseInt() Method

The parseInt() method has two parameters: String s and int radix:

public static int parseInt(String s, int radix)

It returns an integer value of the given string argument in the specified radix given as the second argument. The string argument must be digits in the radix specified. It also throws a NumberFormatException in situations mentioned in Java's official documentation.

2.2. toString() Method

The toString()  method is used in conjunction with the earlier mentioned parseInt() method to convert numbers from one base to another:

public static String toString(int i, int radix)

According to its signature, this method takes two parameters, int i and a radix of type int. The method returns a string representing the value of the specified radix, which is the second argument. Where a second argument is not provided, it uses base 10 as the default value.

3. Converting Number Bases Using Integer Class Methods parseInt() and toString()

As we hinted earlier, there are two approaches for converting a number from one base to another in Java. The first and easiest way would be using the Integer class methods parseInt() and toString() to make this number of conversions from a given base to a target base. Let's create a method that uses both parseInt() and toString() for base conversion:

public static String convertNumberToNewBase(String number, int base, int newBase){
    return Integer.toString(Integer.parseInt(number, base), newBase);
}

Our method, convertNumberToNewBase(), takes three parameters, a string representing digits in a specified radix or a number base system of the second argument of type int. The third argument is an int of the new base for our conversion. The method returns a string in the new base. The parseInt() takes the string argument and its radix and returns an integer value. This integer value is passed on as the first argument of the toString() method, which converts the integer to a string in the new base given in its second argument.

Let's look at an example:

@Test
void whenConvertingBase10NumberToBase5_ThenResultShouldBeDigitsInBase5() {
    assertEquals(convertNumberToNewBase("89", 10, 5), "324");
}

The string “89” is given in base 10 for conversion to base 5. Our method returns a string result “324”, which is indeed a number in the base 5 number system.

4. Converting Number Bases Using a Custom Method

Our other approach for converting between number bases would be writing our own custom method in Java for executing this task. The proposed method should have three parameters, a string of digits, an int specifying base, and another int representing the new base for conversion.

A logical way to achieve this is to create sub-methods to handle smaller aspects of our number conversion code. We'll define a method for converting any number from base 2 to 9 and 16 to decimal (base 10) and another for converting numbers from base 10 to base 2 to 9 and 16:

public static String convertFromDecimalToBaseX(int num, int newBase) throws IllegalArgumentException {
    if ((newBase < 2 || newBase > 10) && newBase != 16) {
        throw new IllegalArgumentException("New base must be from 2 - 10 or 16");
    }
    String result = "";
    int remainder;
    while (num > 0) {
        remainder = num % newBase;
        if (newBase == 16) {
            if (remainder == 10) {
                result += 'A';
            } else if (remainder == 11) {
                result += 'B';
            } else if (remainder == 12) {
                result += 'C';
            } else if (remainder == 13) {
                result += 'D';
            } else if (remainder == 14) {
                result += 'E';
            } else if (remainder == 15) {
                result += 'F';
            } else {
                result += remainder;
            }
        } else {
            result += remainder;
        }
        num /= newBase;
    }
    return new StringBuffer(result).reverse().toString();
}

The convertFromDecimalToBaseX() method takes two parameters, an integer and a new base for conversion. The result is obtained by continuously dividing the integer by the new base and taking the remainder. The method also has a conditional for base 16 numbers. Another method converts from any given base to base 10 with a sub-method for converting base 16 char characters to decimal values:

public static int convertFromAnyBaseToDecimal(String num, int base) {
    if (base < 2 || (base > 10 && base != 16)) {
        return -1;
    }
    int val = 0;
    int power = 1;
    for (int i = num.length() - 1; i >= 0; i--) {
        int digit = charToDecimal(num.charAt(i));
        if (digit < 0 || digit >= base) {
            return -1;
        }
        val += digit * power;
        power = power * base;
    }
    return val;
}
public static int charToDecimal(char c) {
    if (c >= '0' && c <= '9') {
        return (int) c - '0';
    } else {
        return (int) c - 'A' + 10;
    }
}

We combine these methods to have a robust method that converts numbers from any base to another:

public static String convertNumberToNewBaseCustom(String num, int base, int newBase) {
    int decimalNumber = convertFromAnyBaseToDecimal(num, base);
    String targetBase = "";
    try {
        targetBase = convertFromDecimalToBaseX(decimalNumber, newBase);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
    return  targetBase;
}

Let's test our custom method to confirm it works as expected:

@Test
void whenConvertingBase2NumberToBase8_ThenResultShouldBeDigitsInBase8() {
    assertEquals(convertNumberToNewBaseCustom("11001000", 2, 8), "310");
}

The method returns the string “310” when the string “11001000” in base 2 is converted to base 8.

5. Conclusion

In this tutorial, we learned how to convert numbers from one base to another in Java using the java.lang.Integer class methods toString() and parseInt(). We put these two methods into another method for reusability. We also took it a step further by writing our own custom method, which converts a string of digits to its base 10 equivalent and then converts it to another number base.

The entire code for this tutorial can be found over on GitHub.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
guest
0 Comments
Inline Feedbacks
View all comments