Program to convert Decimal to Binary

Description

Convert decimal to binary means convert it in 0,1 format follow below program.

C/C++

/* C Program to convert Decimal to Binary */
//Save it as ConvertDecimalToBinary.c

#include<stdio.h>
int main(){

    int dec, rem, bin=0, count=1;

    printf("Enter a decimal value : ");
    scanf("%d", &dec);

    //Storing the decimal value to temporary variable
    int temp = dec;

    while(dec > 0) {

        //Calculation of remainder
        rem = dec % 2;

        //Calculation of octal value
        bin += (rem * count);

        //storing exponential value
        count *= 10;

        dec /= 2;
    }

    //Restoring the decimal value
    dec = temp;

    printf("Binary value of %d is %d", dec, bin);

    return 0;
}
Input:
Enter a decimal value : 9

Output:
Binary value of 9 is 1001

Java

/* Java Program to convert Decimal to Binary */
//Save it as ConvertDecimalToBinary.java

import java.io.*;
import java.util.Scanner;

public class ConvertDecimalToBinary {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter a decimal value : ");
        int dec = scanner.nextInt();
        
        //Storing the decimal value to temporary variable
        int temp = dec;
        
        int rem, bin=0, count=1;
        
        while(dec > 0) {
            
            //Calculation of remainder
            rem = dec % 2;
            
            //Calculation of octal value
            bin += (rem * count);
            
            //storing exponential value
            count *= 10;
            
            dec /= 2;
        }
        
        //Restoring the decimal value
        dec = temp;
        
        System.out.println("Binary value of "+ dec +" is "+ bin);
        
        
        /* 
            There is predefined function in Java to convert decimal to binary
            Integer.toBinaryString(decimalNumber)
        */
        
    }
}
Input:
Enter a decimal value : 
9

Output:
Binary value of 9 is 1001

Related Programs

1) Program to convert Binary to Decimal
2) Program to convert Binary to Hexa Decimal
3) Program to convert Decimal to Octal
4) Program to convert Octal to Decimal
5) Program to find sum of digits of a number
6) Program to reverse a number
7) Program to calculate Factorial of a Number
8) Program to display multiplication table of a number
9) Program to Display Fibonacci Series
10) Program to Display Fibonacci Series using Recursion
11) Program of Simple Calculator using switch
12) Program to print all Squares of numbers from 1 to given Range
13) Program to find sum of first and last digit of a number
Share Me

Leave a Reply