- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements