HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Is decimal, hexadecimal, octadecimal, binary converter efficient?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
hexadecimaloctadecimaldecimalefficientbinaryconverter

Problem

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  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){

Solution

Disclaimer: I'm new here, so this might not be the type of review people give, but I'm trying to match it as best as I can.

Formatting

A comment explaining the purpose of combineResults(String a, String b) next to the method would be helpful. (Yes, there's one in the main method, but documentation next to the helpers is good, too.)

The same could be said for numConverter(int number)...

Other than that, indentation looks good, braces look fine, etc. :)

Algorithm

In general: You should be passing around StringBuilders or StringBuffers (or chars) instead of Strings. The former are mutable, while the latter isn't mutable. This will save some performance. (e.g. appending is better on memory with the builders and buffers, rather than with raw Strings.)

Main Algorithm

Ok... You took kinda an odd approach to converting bases. Rather than using all those while loops, you should focus on determining the next least significant digit by using the modulus operator followed by division.

For example, in pseudocode:

while(number > 0) {
  nextDigit = number % base; //Get the next digit using modulo
  number /= base; 
  // prepend nextDigit to result String Buffer
}


This makes the combineResults() method unneeded, as prepend is built-in to the StringBuilder.

NumConverter

In the spirit of StringBuilders vs. String, this should return a char rather than a String.

Your current code assumes that the only number ever fed to this method will be less than 16. This could be a problem if it's a larger library, or if you want to expand the bases to more than hexadecimal.

You could use a switch/case construct instead of the else if's...

Or, if you really want to shorten the code, you could do something like (note: this also implements the char return instead of String):

char numConverter(int digit) {
   if (num >= 16 || num < 0) //If we're not given a valid digit
     return 0; //Let the output know somehow...  could throw an exception instead.
   else if (digit <= 10) //If we're dealing with a "normal" digit
     return ((char)num + '0'); //... return the numeric equivalent
   else //We're in extended digit range: we need letters!
     return ((char)digit + 'A' - 10); //Return hex equivalent of 10-15 (A-F)
}

Code Snippets

while(number > 0) {
  nextDigit = number % base; //Get the next digit using modulo
  number /= base; 
  // prepend nextDigit to result String Buffer
}
char numConverter(int digit) {
   if (num >= 16 || num < 0) //If we're not given a valid digit
     return 0; //Let the output know somehow...  could throw an exception instead.
   else if (digit <= 10) //If we're dealing with a "normal" digit
     return ((char)num + '0'); //... return the numeric equivalent
   else //We're in extended digit range: we need letters!
     return ((char)digit + 'A' - 10); //Return hex equivalent of 10-15 (A-F)
}

Context

StackExchange Code Review Q#41831, answer score: 8

Revisions (0)

No revisions yet.