March 6 2017

Java program convert decimal to binary

Java program convert decimal to binary

Decimal number system is a base 10 number system using digits for 0 to 9 whereas binary number system is base 2 and uses 0 and 1.

Algorithm to convert Decimal to Binary number

  1. Divide the decimal number by 2 and store the remainder
  2. Store the quotient back to the input number variable
  3. Repeat step 1 and 2 till quotient becomes zero.
  4. Binary number will be the remainders in above process in reverse order

Example            

Decimal number – 11

Step 1. 11/2 Remainder = 1 Quotient = 5

Step 2. 5/2 Remainder = 1 Quotient = 2

Step 3. 2/2 Remainder = 0 Quotient = 1

Step 4. 1/2 Remainder = 1 Quotient = 0

Binary Number of 11 is the remainders in reverse order: 1011

Program

package com.answersz;

public class JavaConvertDecimalToBinary {

public void printBinaryFormat(int num) {

System.out.print("Decimal Number - " + num);

int binary[] = new int[20];
 int index = 0;
 while (num > 0) {
 binary[index++] = num % 2;
 num = num / 2;
 }

System.out.print(" Binary Number - ");
 for (int i = index - 1; i >= 0; i--) {
 System.out.print(binary[i]);
 }
 System.out.println();
 }

public static void main(String[] args) {

// Java program convert decimal to binary

JavaConvertDecimalToBinary javaConvertDecimalToBinary = new JavaConvertDecimalToBinary();

javaConvertDecimalToBinary.printBinaryFormat(11);

javaConvertDecimalToBinary.printBinaryFormat(25);

javaConvertDecimalToBinary.printBinaryFormat(13);
 }

}

Output

Decimal Number - 11 Binary Number - 1011
Decimal Number - 25 Binary Number - 11001
Decimal Number - 13 Binary Number - 1101

 

 


Copyright © 2014. All rights reserved.

Posted March 6, 2017 by answersz in category Bluej Java Programs for ICSE Class 10 and 9 Practice, Core Java

Leave a Comment

Your email address will not be published. Required fields are marked *

*