Convert one base to other bases in a single Java Program


Let’s say we have an Octal number. To convert Octal to other bases like binary, hexadecimal, etc, the Java code is as follows −

Example

 Live Demo

public class Demo{
   public static String base_convert(String num, int source, int destination){
      return Integer.toString(Integer.parseInt(num, source), destination);
   }
   public static void main(String[] args){
      String my_num = "345";
      int source = 8;
      int destination = 2;
      System.out.println("Converting the number from octal to binary: "+ base_convert (my_num, source, destination));
      destination = 10;
      System.out.println("Converting the number from octal to decimal : "+ base_convert (my_num, source, destination));
      destination = 16;
      System.out.println("Converting the number from octal to hexadecimal: "+ base_convert (my_num, source, destination));
   }
}

Output

Converting the number from octal to binary: 11100101
Converting the number from octal to decimal : 229
Converting the number from octal to hexadecimal: e5

A class named Demo contains a function named ‘base_convert’ is defined. This function parses the integer from source base to the destination base, converts it into a string and returns it as output. In the main function, the value for number, for source base and for different destination bases are defined. The ‘base_convert’ function is called with the number, source and destination as parameters. Relevant output is displayed.

Updated on: 07-Jul-2020

839 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements