1

How can we convert int number, a decimal, to Binary? I'm learning Java & have the code below. Any advice? Thanks!

public static int decimalToBinary(int number) {
int result = 0;
while(number > 0){


    int mod = number % 2;
    result = result * 1 + mod;

    number /= 2;
}

return result;
}
Lanie909
  • 849
  • 1
  • 8
  • 11

2 Answers2

2

You can use the Integer.toBinaryString() method as follows,

int n = 100;
System.out.println(Integer.toBinaryString(n));

The Integer.toBinaryString() takes an int as a parameter and returns a String, so you can also do the following:

int n=100;
String s = Integer.toBinaryString(n);
System.out.println(s);
Adit A. Pillai
  • 647
  • 1
  • 10
  • 22
0

This will print it out to the screen, but you can just as easily assign it to a variable.

import java.util.Scanner;

public class ReversedBinary {

    public static void main(String[] args) {
        int number; 

        Scanner in = new Scanner(System.in);

        System.out.println("Enter a positive integer");
        number = in.nextInt();

        if (number < 0) {
            System.out.println("Error: Not a positive integer");
        } else { 

            System.out.print("Convert to binary is:");
            //System.out.print(binaryform(number));
            printBinaryform(number);
        }
    }

    private static void printBinaryform(int number) {
        int remainder;

        if (number <= 1) {
            System.out.print(number);
            return;   // KICK OUT OF THE RECURSION
        }

        remainder = number %2; 
        printBinaryform(number >> 1);
        System.out.print(remainder);
    }
}
JordanGS
  • 3,966
  • 5
  • 16
  • 21