Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a number from base 10 to N

Tags:

java

This code is a part of a project that I have to develop. I need to write a java method that converts a number (base 10) to another number in n base. This is the code of the class:

public class converter {

    public int from_10_to_n(int base, int newbase) {

       int k = 0;
       String res = "";
       String output = "";

       do {                        //Below I explain what I'm doing here
        base /= newbase;   
        k = base % newbase;
        res += String.valueOf(k);
       } while (base != 0);

       for(int i=res.length()-1; i>-1; i--) {
        output += res.charAt(i);
       }

       return Integer.parseInt(output);
    }

I thought to make the program in this way:

enter image description here

The do {} while(); loop divides the numbers and saves in k the remainders. Then I make a for loop that reverses the string res (which has the reminders).

By the way when I call the method in my main, I am missing the last digit. I mean:

converter k = new converter();
int e = k.from_10_to_n(a /*base 10 number*/, b /*Base n number*/);

System.out.println(a+" -> "+b+" is " + e);

With this code, if I want to convert 231 to base 4 I have 321 as result instead of 3213. I have checked my code but I cannot find a solution. Any idea?

I have the same error with other bases. For example 31 (base 10) is 11111 (base 2) but my program returns 1111.

like image 614
Alberto Rossi Avatar asked Jan 11 '23 06:01

Alberto Rossi


2 Answers

Flip the order of the first 2 lines in the loop; by doing the division first, you lose the first remainder. But then you'll need to handle the last remainder.

like image 91
Scott Hunter Avatar answered Jan 26 '23 19:01

Scott Hunter


The problem lies here:

base /= newbase;
k = base % newbase;

Try this with some real numbers, like 231 and base 4 in your example.

base /= newbase

Now base is 57 and your k will be incorrect. You should get the remainder first, then divide:

k = base % newbase;
base /= newbase;

There are also some style problems with your code which you should consider correcting:

  • base doesn't really hold any base, just input value - maybe rename it to input or something like that?
  • Mixed indentation. Your loops are indented with one space, while the rest of the code has four.
like image 40
gronostaj Avatar answered Jan 26 '23 19:01

gronostaj