Search code examples
javaradix

Converting a number to a user chosen base


I want to make a thing that takes in a number, and a base system, such that it will convert the number to that number in a different base from base 2 to base 16.

E.g. stdin would be 67 and 2, meaning the user wants the program to change the number 67 into binary form. stdout would be 1000010.

So I made the following code to get it going at first. This program takes in a number and converts it to binary format.

public class ChangeofBase { 
    public static void main(String[] args) { 
        // read in the command-line argument
        int n = Integer.parseInt(args[0]); 
        // set v to the largest power of two that is <= n
        int v = 1; 
        while (v <= n/2) {
            v *= 2;
        }
        // check for presence of powers of 2 in n, from largest to smallest
        while (v > 0) {
            // v is not present in n 
            if (n < v) {
                System.out.print(0);
            }

            // v is present in n, so remove v from n
            else {
                System.out.print(1);
                n -= v;
            }
            // next smallest power of 2
            v /= 2;
        }
        System.out.println();
    }
}

How can I modify the above code to perform the following function?

Take in a number n and a base k so that n will be converted to a number in base k

Once again, k has to be between 2 and 16. Base 2 and base 16. Binary and hexadecimal. Thank you!

Edit: I would like to do this without using built-in functions. Hardcoding
Edit 2: I am new to Java. So I would like to stick to the basic stuff such as defining variables, while loops and foor loops, if-else, and printing. and parsing command line args. I believe thats all we need for this program, though correct me if i'm wrong


Solution

  • Apart from the Java built in function, You can use simple division and modulus operations in Java to achieve that.

    public class IntBaseConverter {
    public static void main(String[] args) {
        convert(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
    }
    
    public static void convert(int decimalValue, int base) {
        String result = "";
        while (decimalValue >= base) {
            result = decimalValue % base + result;
            decimalValue /= base;
        }
        result = decimalValue + result;
    
        System.out.println(result);
    }
    }