Biazs
Biazs

Reputation: 13

Java Integer to Binary Converter Code

I am trying to write a basic calculator. One of the things I want my calculator to have is a base arithmetic converter that gives an output when you input a base 10 integer.

I tried to write code for it on my own and it took nearly 3 hours just to figure out how to convert a number to a given base and it works good enough so far but I have one problem - when I try to convert an integer to base 2 (binary) my calculator does not work for numbers bigger than 1025.

I thought the problem was because there is a max value an integer can hold or something so I tried "BigInteger" but since it does not support remainder "%" operation I could not make it work.

else if(c.equals("Base")) {
    g = 0;
    l = 0;
    System.out.println("Enter the number (Integer) you want to convert");
    f = scan.nextInt();
    System.out.println("Enter the arithmetic base you want for your new number");
    m = scan.nextInt();
    for (;f>=1;) {
        h=f%m; 
        f=f/m;
        k = (int)Math.pow(10,g);
        g++;
        l =l + (h*k);
    }
    System.out.println(l);
}

Sorry if the code is really bad and there are more efficent ways, i just wanted it to be mine instead of looking it up.

Upvotes: 0

Views: 332

Answers (4)

Nathanael Oliver
Nathanael Oliver

Reputation: 36

If you want to use the BigInteger class, you can use the mod method instead of "%".

BigInteger myBigInteger = new BigInteger("943838859");
System.out.println(myBigInteger.mod(BigInteger.TEN));

This will print 9.

Upvotes: 1

Ashraff Ali Wahab
Ashraff Ali Wahab

Reputation: 1108

You can do this in a 3 lines of code using a recursive funtion,

public static String convertToBase(int n, int b) {
    return n > 0 ? (convertToBase(n / b, b) + n % b) : "";
}

Upvotes: 0

user8491011
user8491011

Reputation:

This is the way I've tried myself (modulo/divide/add):

    int decimalOrBinary = 345;
    StringBuilder builder = new StringBuilder();

    do {
        builder.append(decimalOrBinary % 2);
        decimalOrBinary = decimalOrBinary / 2;
    } while (decimalOrBinary > 0);

    System.out.println(builder.reverse().toString()); //prints 101011001

Upvotes: 0

Eran
Eran

Reputation: 393821

It's not a good idea to store the "binary representation" in an int variable, since that limits you to 10 digits.

Instead, you can use a String variable to hold the result:

String l = "";
while (f > 0) {
    h = f % m; 
    f = f / m;
    l = h + l;
}
System.out.println(l);

Upvotes: 0

Related Questions