user3418378
user3418378

Reputation:

how to convert different number systems to base ten in the simplest way

I have searched for this question on the website but do not understand most of the solutions posted. my question is; i have a method:

public static int convertToDecimal(int number, int base)

it will receive a number and base, then multiply them thus:

(1023, 4) passed to the method will be (1 * Math.pow(4,3)) + (0* Math.pow(4,2))+(2* Math.pow(4,1))+(3* Math.pow(4,0)) will return 75.

please I am very new to java and do not yet understand the sophisticated methods of doing this. the goal is to understand how to do the iriteration. thanks

Upvotes: 0

Views: 243

Answers (2)

Arpit Jain
Arpit Jain

Reputation: 782

Method Integer.parseInt(String,int) does exactly what your are looking for.

Integer.parseInt("1023",4) //returns 75

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503090

An integer value itself (e.g. an int) doesn't have a base, really. It's just a number.

Bases are mostly important for textual representations. (They're also important in floating point numbers as that determines what sort of point is floating, but let's leave that aside for the moment.) So it would make sense to have:

public static String convertToDecimal(String input, int base)

Or even:

public static int convertFromBase(String input, int base)

But your current signature doesn't make much sense. 1023 is not the same as "1023"... it's just a number.

Fortunately, Java has the second of these signatures built in, as Integer.parseInt(String, int), so you don't need to do it yourself. If you do want to do it yourself, I would write it something like:

public static int convertFromBase(String input, int base) {
    int multiplier = 1;
    int result = 0;
    for (int index = input.length() - 1; index >= 0; index--) {
        // This will handle hex for you. TODO: Validation!
        int digitValue = Character.digit(input.charAt(index), base);
        result += digitValue * multiplier;
        multiplier *= base;
    }
    return result;
}

Upvotes: 2

Related Questions