ADVERTISEMENT
ADVERTISEMENT

Java program to convert number from Decimal to Binary

This program will convert integer (Decimal) number to its equivalent Binary Number.
There are two programs:
1) Without using any predefine method and
2) Using Integer.toBinaryString() method.

Without using any predefine method

//java program to convert decimal to binary

import java.util.*;

public class ConvDec2Bin {
  public static void main(String args[]) {
    int num, counter = 0;
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter any integer number: ");
    num = sc.nextInt();

    //to store maximum 32 bits of a number
    int binaryVal[] = new int[32];

    while (num > 0) {
      binaryVal[counter++] = num % 2;
      num = num / 2;
    }

    /*print binary values stored in binaryVal*/
    for (int i = counter - 1; i >= 0; i--) {
      System.out.print(binaryVal[i]);
    }
  }
}

Output:

Complie 	:	javac ConvDec2Bin.java
Run		:	java ConvDec2Bin
Output
Enter any integer number: 12345
11000000111001

Using Integer.toBinaryString() method

//java program to convert decimal to binary

import java.util.*;

public class ConvDec2Bin {
  public static void main(String args[]) {
    int num;
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter any integer number: ");
    num = sc.nextInt();

    String str = Integer.toBinaryString(num);
    System.out.println("Binary number is : " + str);
  }
}

Output:

Complie 	:	javac ConvDec2Bin.java
Run		:	java ConvDec2Bin
Output
Enter any integer number: 12345
Binary number is : 11000000111001

Java Number System Conversion Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.