import java.io.*;
public class BaseTransform
{
private final BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
public BaseTransform(){
try{
System.out.print("Enter any integer: ");
int input=Integer.parseInt(this.getInput());
System.out.print("Enter a base[2...16]: ");
int base=Integer.parseInt(this.getInput());
String answer=this.transform(input,base);
if(answer!=null){
System.out.println(""+input+" at base "+base+" is "+answer+".");
}else{
System.out.println("Error!");
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
BaseTransform bt=new BaseTransform();
}
private String transform(int data,int base){
if(base>16 || base<2)return null;
String answer="";
if(base==10){
return ""+data; //base 10 is decimal
}else{
try{
while((data/base)>0){
answer=this.checkResult((data%base),base)+answer;
data=data/base;
}
answer=this.checkResult((data%base),base)+answer;
return answer;
}catch(Exception e){
e.printStackTrace();
}
}
return null; //means error
}
private String checkResult(int digit,int base){
//for bases greater than or equals 10 start printing letters
if(base>=10){
//we will analyze each digit if greater than 10 again
if(digit>=10){
return ""+(char)(digit-10+65);
}
}
return ""+digit;
}
private String getInput(){
try{
return buffer.readLine();
}catch(IOException e){
e.printStackTrace();
}
return null; //means error
}
}
rythreion 0 Newbie Poster
peter_budo 2,532 Code tags enforcer Team Colleague Featured Poster
jwenting 1,889 duckman Team Colleague
rythreion 0 Newbie Poster
peter_budo 2,532 Code tags enforcer Team Colleague Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.