I have made a method which takes two parameters: the value to convert and the base. Based upon those two parameters my method is adjusted (with several helper methods) to change the desired decimal number to a number with a different base.
Is this code practical and clean? If not, what should I change to make it better?
public String baseConversion(int base, int value){
String finalResult = "";
String tempResult = "";
int countLength = 0, countFit = 0; // countLength counts the length of the tempResult string in order to know how many '0' to add. countFit counts how many times the tempValue fits into the current parameter 'value'
int placeValue; // Records the place value. ex 245: '2' is in the hundreds place value
int tempValue = 0;
while (value > 0){
placeValue = 1;
// calculates the highest power that fits in the value (takes desired base into account)
while (value > placeValue){
placeValue*=base;
countLength++;
}
if (value!=placeValue){
countLength--; // subtract to account for the value in the tempResult that is not '0'
placeValue/=base; // divide back as the previous while loop went one placeValue higher than needed in order to break out
}
//figures out how many times the placeValue can fit into the value
while (tempValue+placeValue <= value){
tempValue+=placeValue;
countFit++;
}
if (base==16){
tempResult += numConverter(countFit);
}
if (base==8 || base == 2 || base == 10){
tempResult += String.valueOf(countFit);
}
// adds zeros to the rest of the string
while (countLength > 0){
tempResult+="0";
countLength--;
}
// takes the current tempResult and combines with previous. ex combine 10000 with 100 = 10100
finalResult = combineResults(finalResult, tempResult);
value -= tempValue;
countFit=0;
tempValue=0;
tempResult="";
}
return finalResult;
}
Helper methods:
private String numConverter(int number){
// only for hexadecimal
if(number == 10){
return "A";
}else if (number == 11){
return "B";
}else if (number == 12){
return "C";
}else if (number == 13){
return "D";
}else if(number == 14){
return "E";
}else if (number == 15){
return "F";
}else {
return String.valueOf(number);
}
}
private String combineResults(String a, String b){
String result = "";
int indexA = 0, indexB = 0;
int aTempLength = a.length(), bTempLength = b.length();
if (a.length() > b.length()){
while (aTempLength > bTempLength){
result+=a.charAt(indexA);
indexA++;
aTempLength--;
}
}else {
while (bTempLength > aTempLength){
result+=b.charAt(indexB);
indexB++;
bTempLength--;
}
}
while (aTempLength > 0){
if (String.valueOf(a.charAt(indexA)).equals("0")){
result+=b.charAt(indexB);
indexA++;
indexB++;
}else {
result+=a.charAt(indexA);
indexA++;
indexB++;
}
aTempLength--;
}
return result;
}