简体   繁体   中英

How to convert decimal to a higher base and vice versa

As a programming assignment for my java CSC class I have written the following code to convert a number and its base to a decimal number and then to a desired number and base.

    public static int baseten(int number,int basein){
    int power = 0;
    int baseten = 0;
    while (number > 0) {
        int finalDigit = number % 10;
        int product = finalDigit*(int)Math.pow(basein, power);
        baseten += product;
        number = number / 10;
        power++;
    }
    return(baseten);
}
public static String convert (int decimal, int baseout){
    String result = "";
    while (decimal > 0){
        //if baseout
        int remainder = decimal % baseout;
        decimal = decimal / baseout;
        result = remainder + result;
    }
    return(result);
}

The question is how to convert a number to a base higher than ten within this code? I assume maybe a char[], but I'm not very good with arrays right now and can't imagine what that might look like. I don't think I can use toString's or parseInt's. Any help would be appreciated. Thanks in advance.

You are almost there. What you could do is insert an if/else statement to determine whether the remainder is greater or equal to ten or not and act accordingly. If it isn't, do what you're doing right now. If it is, then you need to add a char to your string. This char must be (remainder-10) + 65, since 65 is capital A on the ascii table and you need to know how many digits above ten remainder is and add that to A. This could be simplified to simply adding 55, but that is less readable in my opinion. Then, just add that char to the string instead of adding the int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM