Majd Ramadan
Majd Ramadan

Reputation: 33

convert decimal to any base java

can anybody help me in this question

Write a program that includes in its MainClass the following:

Hints:

  1. Remember that in order to convert a decimal number that includes only an integer part to a base n, you need to use repeated integer division of successive quotients on n saving the remainder in each step until the quotient is zero.
  2. Remember that numbering systems with bases 11-16 use letters in order to continue counting after the digit 9. For example, the numbering system with base 12 has the following digits: {0,1,2,3…..,9,A,B}

this is my code . i know it's not correct :(

public static void main(String[] args) {
    convertFromDecimal (1,2);
}

public static String convertFromDecimal(int number, int base) {
 String S="  ";
    int[] converted =new int [base] ;
    while (number>0) {
        int R;
        R=number%base;
        number=number/base;
        char Rchar ;
        switch (R){
            case 10 : Rchar='A';
            case 11 : Rchar='B';
            case 12 : Rchar='C';
            case 13 : Rchar='D';
            case 14 : Rchar='E';
            case 15 : Rchar='F';

        }
            for (int i=0;i<base;i++) 
            {
        converted[i]=R;
                R=number%base;
        }
        for (int m=0;m<base ;m++)
   System.out.print(S +converted[m]);

    }
    return S;        
}

Upvotes: 0

Views: 8217

Answers (1)

csalmhof
csalmhof

Reputation: 1860

I would convert it like described here: http://www.robotroom.com/NumberSystems3.html

A working example (i would prefer a while loop here, but the requirement says for:

public static void main(String [] args) throws Exception {

    System.out.println(convertFromDecimal(15,3));
}

public static String convertFromDecimal(int number, int base) {
    String result = "";

    int lastQuotient = 0;

    for(int operatingNumber = number;operatingNumber > base; operatingNumber = operatingNumber/base) {
        result = getRepresantationOfLowIntValue(operatingNumber%base) + result;
        lastQuotient = operatingNumber/base;
    }

    result = getRepresantationOfLowIntValue(lastQuotient) + result;

    return result;
}

The requirement in hint 1 you can find inside the while-loop. The requirement in hint 2 you can find below.

private static String getRepresantationOfLowIntValue(int toConvert) {
    if(toConvert >= 0 && toConvert < 10) {
        return "" + toConvert;
    }

    switch(toConvert) {
        case 10 : return "A";
        case 11 : return "B";
        case 12 : return "C";
        case 13 : return "D";
        case 14 : return "E";
        case 15 : return "F";
    }

    return "Error, cannot transform number < 0 or > 15";
    //throw new IllegalArgumentException("cannot transform number < 0 or >15");
}

Upvotes: 2

Related Questions