Skip to main content

How to convert the Base of a Decimal Number in Java

Points To Remember

You can convert the number from decimal to any base by dividing the number by the base till the number is either 0 or less than the base it self and counting the remainders in a reverse order.

Program : Convert the base of a Decimal Number

import java.util.Scanner;

class ConvertBase{

public static void main(String args[]){

Scanner sc = new Scanner(System.in);

System.out.println("Enter the Original NUmber");
int originalNumber = sc.nextInt();

System.out.println("Enter the base for conversion");
int base = sc.nextInt();

String convertedNumber = new ConvertBase().convert(originalNumber,base);

System.out.println("Original Number = "+originalNumber);
System.out.println("Converted NUmber = "+convertedNumber);
}



public String convert(int original, int base){
String number = "";
String converted ="";

while(original != 0){
int digit = original % base;
original /= base;
number += digit;
}
for(int itr=number.length()-1;itr>=0; itr--)
converted += number.charAt(itr);
return converted;
}

}
The above program will give the following output
Enter the Original NUmber
45
Enter the base for conversion
5
Original Number  = 45
Converted NUmber = 140
You can convert a decimal number to any base with this code.

Comments