One of my friend was looking for a Java program which can convert the given number of any base to any desired base number. So I thought to write a simple program for this.
Overview
This post shows a compact Java example that converts a number given in one base to another base. The simple implementation uses Integer.parseInt and Integer.toString, which is convenient for numbers that fit in a 32-bit signed int. Below you'll find the original code, an explanation, example I/O, and a recommended improved version that supports arbitrarily large integers using BigInteger.
How it works (quick summary)
- Read the number as a String and the source and target bases as integers.
- Use Integer.parseInt(str, fromBase) to parse the input string into an int.
- Use Integer.toString(value, toBase) to convert the integer into the target base representation.
Note: Integer.parseInt and Integer.toString support bases from 2 to 36. Digits greater than 9 are represented as letters a–z (for example, 10 -> 'a').
Short example I/O
- Input number: 1010
- From base: 2
- To base: 10
- Converted value: 10
Original (simple) code examples and explanation
The essential one-line conversion the post demonstrates is:
Integer.toString(Integer.parseInt(str, fromBase), toBase)
This converts the string str from base fromBase to a string representation in base toBase.
Below is the whole program as presented in the original post (kept unchanged):
package com.chapter2;
import java.util.Scanner;
public class conversion {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Enter the number");
Scanner marut= new Scanner(System.in);
String number=marut.nextLine();
System.out.println("Enter the Base of the number");
int fromBase = marut.nextInt();
System.out.println("Enter the Base to convert");
int toBase = marut.nextInt();
String result=convertFromBaseToBase(number,fromBase,toBase);
System.out.println("Converted value is: "+result);
}
public static String convertFromBaseToBase(String str, int fromBase, int toBase){
//convert from one base to another
return Integer.toString(Integer.parseInt(str, fromBase), toBase);
}
}
Example screenshot
Download
You can download this program here:
Limitations and notes
- Range: Integer.parseInt returns a 32-bit signed int. Very large numbers will cause NumberFormatException or incorrect results if they exceed integer range.
- Supported bases: 2–36. Characters beyond 'z' are not supported by these methods.
- Input validation: The original example does not catch parsing exceptions; consider wrapping parsing in try/catch and validating base range.
Improved version (supports large numbers using BigInteger)
If you expect numbers larger than 32-bit range, use BigInteger. The following method converts between bases using BigInteger for arbitrary-precision integers:
// Example conversion using BigInteger
import java.math.BigInteger;
public static String convertUsingBigInteger(String str, int fromBase, int toBase) {
// Validate bases
if (fromBase < Character.MIN_RADIX || fromBase > Character.MAX_RADIX
|| toBase < Character.MIN_RADIX || toBase > Character.MAX_RADIX) {
throw new IllegalArgumentException("Bases must be between " + Character.MIN_RADIX + " and " + Character.MAX_RADIX);
}
// Parse with BigInteger and reformat
BigInteger value = new BigInteger(str, fromBase);
return value.toString(toBase);
}
Add simple validation and exception handling around user input in the main method:
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter the number: ");
String number = sc.nextLine().trim();
System.out.print("Enter the Base of the number: ");
int fromBase = Integer.parseInt(sc.nextLine().trim());
System.out.print("Enter the Base to convert: ");
int toBase = Integer.parseInt(sc.nextLine().trim());
String result = convertUsingBigInteger(number, fromBase, toBase);
System.out.println("Converted value is: " + result);
} catch (NumberFormatException | IllegalArgumentException e) {
System.err.println("Invalid input: " + e.getMessage());
}
This approach:
- Avoids Integer overflow by using arbitrary precision.
- Ensures cleaner input handling (use nextLine + parse to avoid Scanner newline quirks).
- Validates base ranges with Character.MINRADIX and Character.MAXRADIX (2–36).
Summary / Recommendations
- The original code is concise and useful for small integers; keep it as a quick snippet.
- For production or larger numbers, replace Integer.parseInt/Integer.toString with BigInteger to avoid range issues.
- Add simple validation and exception handling so users get friendly error messages.
- Improve on-page SEO by adding this structured content, a short meta description, and internal links to related Java topics.
That's it. The examples and download link above are the same as in the original post.
No comments:
Post a Comment