Program for Decimal to Binary Conversion

29 Jun, 2022
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent binary number.
Examples: 
 
Input : 7
Output : 111

Input : 10
Output : 1010

Input: 33
Output: 100001
For Example: If the decimal number is 10. Step 1: Remainder when 10 is divided by 2 is zero. Therefore, arr[0] = 0. Step 2: Divide 10 by 2. New number is 10/2 = 5. Step 3: Remainder when 5 is divided by 2 is 1. Therefore, arr[1] = 1. Step 4: Divide 5 by 2. New number is 5/2 = 2. Step 5: Remainder when 2 is divided by 2 is zero. Therefore, arr[2] = 0. Step 6: Divide 2 by 2. New number is 2/2 = 1. Step 7: Remainder when 1 is divided by 2 is 1. Therefore, arr[3] = 1. Step 8: Divide 1 by 2. New number is 1/2 = 0. Step 9: Since number becomes = 0. Print the array in reverse order. Therefore the equivalent binary number is 1010.
The below diagram shows an example of converting the decimal number 17 to an equivalent binary number. 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Below is the implementation of the above idea.  
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to convert a decimal// number to binary number #include <iostream>using namespace std; // function to convert decimal to binaryvoid decToBinary(int n){    // array to store binary number    int binaryNum[32];     // counter for binary array    int i = 0;    while (n > 0) {         // storing remainder in binary array        binaryNum[i] = n % 2;        n = n / 2;        i++;    }     // printing binary array in reverse order    for (int j = i - 1; j >= 0; j--)        cout << binaryNum[j];} // Driver program to test above functionint main(){    int n = 17;    decToBinary(n);    return 0;}
// C Code to convert Decimal number into Binary #include <stdio.h> void decToBinary(int n){    // array to store binary number    int binaryNum[32];      // counter for binary array    int i = 0;    while (n > 0) {        // storing remainder in binary array        binaryNum[i] = n % 2;        n = n / 2;        i++;    }      // printing binary array in reverse order    for (int j = i - 1; j >= 0; j--)        printf("%d", binaryNum[j]);}  // Driver program to test above functionint main(){    int n = 17;    decToBinary(n);    return 0;}
// Java program to convert a decimal// number to binary numberimport java.io.*; class GFG {    // function to convert decimal to binary    static void decToBinary(int n)    {        // array to store binary number        int[] binaryNum = new int[32];         // counter for binary array        int i = 0;        while (n > 0) {            // storing remainder in binary array            binaryNum[i] = n % 2;            n = n / 2;            i++;        }         // printing binary array in reverse order        for (int j = i - 1; j >= 0; j--)            System.out.print(binaryNum[j]);    }     // driver program    public static void main(String[] args)    {        int n = 17;        decToBinary(n);    }} // Contributed by Pramod Kumar
# Python3 program to convert a# decimal number to binary number # function to convert# decimal to binarydef decToBinary(n):         # array to store    # binary number    binaryNum = [0] * n;     # counter for binary array    i = 0;    while (n > 0):         # storing remainder        # in binary array        binaryNum[i] = n % 2;        n = int(n / 2);        i += 1;     # printing binary array    # in reverse order    for j in range(i - 1, -1, -1):        print(binaryNum[j], end = ""); # Driver Coden = 17;decToBinary(n); # This code is contributed by mits
// C# program to convert a decimal// number to binary numberusing System; public class GFG {     // function to convert decimal    // to binary    static void decToBinary(int n)    {        // array to store binary number        int[] binaryNum = new int[32];         // counter for binary array        int i = 0;        while (n > 0) {            // storing remainder in            // binary array            binaryNum[i] = n % 2;            n = n / 2;            i++;        }         // printing binary array        // in reverse order        for (int j = i - 1; j >= 0; j--)            Console.Write(binaryNum[j]);    }     // Driver Code    public static void Main()    {        int n = 17;        decToBinary(n);    }} // This code is contributed by Sam007.
<?php// PHP program to convert a decimal// number to binary number // function to convert// decimal to binaryfunction decToBinary($n){    // array to store    // binary number    $binaryNum;     // counter for binary array    $i = 0;    while ($n > 0)    {         // storing remainder        // in binary array        $binaryNum[$i] = $n % 2;        $n = (int)($n / 2);        $i++;    }     // printing binary array    // in reverse order    for ($j = $i - 1; $j >= 0; $j--)        echo $binaryNum[$j];} // Driver Code$n = 17;decToBinary($n); // This code is contributed by m_kit?>
<script> // Javascript program to convert a decimal// number to binary number // function to convert decimal to binaryfunction decToBinary(n){    // array to store binary number    let binaryNum = new Array(32);     // counter for binary array    let i = 0;    while (n > 0) {         // storing remainder in binary array        binaryNum[i] = n % 2;        n = Math.floor(n / 2);        i++;    }     // printing binary array in reverse order    for (let j = i - 1; j >= 0; j--)        document.write(binaryNum[j]);} // Driver program to test above function    let n = 17;    decToBinary(n);     // This code is contributed by Mayank Tyagi </script>
10001
Time complexity: O(logn) 
Auxiliary Space: O(1) 
We can use bitwise operators to do the above job. Note that bitwise operators work faster than arithmetic operators used above.
C++
C
Java
Python3
C#
PHP
Javascript
// CPP program to Decimal to binary conversion// using bitwise operator// Size of an integer is assumed to be 32 bits#include <iostream>using namespace std; // Function that convert Decimal to binaryint decToBinary(int n){    // Size of an integer is assumed to be 32 bits    for (int i = 31; i >= 0; i--) {        int k = n >> i;        if (k & 1)            cout << "1";        else            cout << "0";    }} // driver codeint main(){    int n = 32;    decToBinary(n);}
// C language to convert Decmial to binary number// using bitwise operator// Size of an integer is assumed to be 32 bits #include <stdio.h> // Function that convert Decimal to binaryint decToBinary(int n){    // Size of an integer is assumed to be 32 bits    for (int i = 31; i >= 0; i--) {        int k = n >> i; //right shift        if (k & 1) // helps us know the state of first bit        else            printf("0");    }} // driver codeint main(){    int n = 32;    decToBinary(n);}
// Java program to Decimal to binary conversion// using bitwise operator// Size of an integer is assumed to be 32 bits class gfg {    // Function that convert Decimal to binary    public void decToBinary(int n)    {        // Size of an integer is assumed to be 32 bits        for (int i = 31; i >= 0; i--) {            int k = n >> i;            if ((k & 1) > 0)                System.out.print("1");            else                System.out.print("0");        }    }} class geek {    // driver code    public static void main(String[] args)    {        gfg g = new gfg();        int n = 32;        g.decToBinary(n);    }}// This code is contributed by mits
# Python3 program to Decimal# to binary conversion using# bitwise operator # Size of an integer is # assumed to be 32 bits # Function that convert# Decimal to binarydef decToBinary(n):         # Size of an integer is    # assumed to be 32 bits    for i in range(31, -1, -1):        k = n >> i;        if (k & 1):            print("1", end = "");        else:            print("0", end = ""); # Driver Coden = 32;decToBinary(n); # This code is contributed by mits
// C# program to Decimal to binary conversion// using bitwise operator// Size of an integer is assumed to be 32 bitsusing System;class gfg {    // Function that convert Decimal to binary    public void decToBinary(int n)    {        // Size of an integer is assumed to be 32 bits        for (int i = 31; i >= 0; i--) {            int k = n >> i;            if ((k & 1) > 0)                Console.Write("1");            else                Console.Write("0");        }    }} class geek {    // driver code    public static int Main()    {        gfg g = new gfg();        int n = 32;        g.decToBinary(n);        return 0;    }}
<?php// PHP program to Decimal to binary conversion// using bitwise operator // Size of an integer is assumed// to be 32 bits // Function that convert Decimal to binaryfunction decToBinary($n){         // Size of an integer is    // assumed to be 32 bits    for ( $i = 31; $i >= 0; $i--)    {        $k = $n >> $i;        if ($k & 1)            echo "1";        else            echo "0";    }}     // Driver Code    $n = 32;    decToBinary($n); // This code is contributed by aj_36?>
<script> // javascript program to Decimal to binary conversion// using bitwise operator// Size of an integer is assumed to be 32 bits      // Function that convert Decimal to binary    function decToBinary(n)    {        // Size of an integer is assumed to be 32 bits        for (i = 31; i >= 0; i--) {            var k = n >> i;            if ((k & 1) > 0)                document.write("1");            else                document.write("0");        }    }     // driver code    var n = 32;    decToBinary(n); // This code contributed by Princi Singh </script>
00000000000000000000000000100000
Time complexity: O(1) 
loop iterates constant(32) number of times everytime even for small number 
Auxiliary Space: O(1)
It’s another efficient approach to converting Decimal to binary using the right shift(>>) and And(&) operator. Here we’ll use only Binary Operators which usually are very fast in computation.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; string DecimalToBinary(int num){    string str;      while(num){      if(num & 1) // 1        str+='1';      else // 0        str+='0';      num>>=1; // Right Shift by 1     }         return str;} void reverse(string str){  for(int i=str.size()-1 ; i>=0 ; i--)   cout<< str[i];} int main() {    int num = 59;    cout<< "Binary of num 59 is: ";      reverse( DecimalToBinary(num) );    return 0;}
// Java program to implement the// above approachimport java.io.*; class GFG{   // the converts decimal to binary base  static String DecimalToBinary(int num)  {    String str = "";    while (num > 0) {      if ((num & 1) == 1) // 1        str += '1';      else // 0        str += '0';      num >>= 1; // Right Shift by 1    }    return str;  }   // reverse the string  static void reverse(String str)  {    for (int i = str.length() - 1; i >= 0; i--)      System.out.print(str.charAt(i));  }  public static void main(String[] args)  {    int num = 59;    System.out.print("Binary of num 59 is: ");    reverse(DecimalToBinary(num));  }} // This code is contributed by phasing17
# Python3 program to implement the above approach# function to convert the decimal number# to binary numberdef DecimalToBinary(num):    strs = ""    while num:        # if (num & 1) = 1        if (num & 1):            strs += "1"        # if (num & 1) = 0        else:            strs += "0"        # right shift by 1        num >>= 1    return strs # function to reverse the stringdef reverse(strs):    print(strs[::-1]) # Driver Codenum = 59print("Binary of num 59 is:", end=" ")reverse(DecimalToBinary(num)) # This code is contributed by phasing17
// C# program to implement the// above approach using System; public class GFG{       // this converts decimal to binary base    public static string DecimalToBinary(int num)    {        string str = "";        while (num > 0) {            if ((num & 1) == 1) // 1                str += '1';            else // 0                str += '0';            num >>= 1; // Right Shift by 1        }        return str;    }    // reverse the string    public static void reverse(String str)    {        for (int i = str.Length - 1; i >= 0; i--)            Console.Write(str[i]);    }    // Driver Code    public static void Main(string[] args)    {        int num = 59;        Console.Write("Binary of num 59 is: ");        reverse(DecimalToBinary(num));    }} // this code was contributed by phasing17
<script>// JavaScript program to implement the approach// function to convert decimal to binaryfunction DecimalToBinary(num){    var str = "";    while (num)    {             // adding the result of num & 1 to str        if (num & 1) // 1            str += '1';        else // 0            str += '0';                     // Right Shift by 1        num >>= 1;    }    return str;} // function to print reverse of strfunction reverse(str){    var res = "";    for (var i = str.length - 1; i >= 0; i--)        res += (str[i]);    document.write(res);} // Driver Codevar num = 59;document.write("Binary of num " + num + " is: "); // function callreverse(DecimalToBinary(num)); // This code is contributed by phasing17</script>
Binary of num 59 is: 111011
Time Complexity:  O(log n)
Auxiliary Space: O(1) 
Decimal to binary conversion can also be done without using arrays. 
C++
C
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <cmath>#include <iostream>using namespace std; #define ull unsigned long long int // Function to return the binary// equivalent of decimal value Nint decimalToBinary(int N){    // To store the binary number    ull B_Number = 0;    int cnt = 0;    while (N != 0) {        int rem = N % 2;        ull c = pow(10, cnt);        B_Number += rem * c;        N /= 2;        // Count used to store exponent value        cnt++;    }    return B_Number;} // Driver codeint main(){    int N = 17;    cout << decimalToBinary(N);    return 0;} // This code is contributed by Sania Kumari Gupta (kriSania804)
// C implementation of the approach#include <math.h>#include <stdio.h> #define ull unsigned long long int // Function to return the binary// equivalent of decimal value Nint decimalToBinary(int N){    // To store the binary number    ull B_Number = 0;    int cnt = 0;    while (N != 0) {        int rem = N % 2;        ull c = pow(10, cnt);        B_Number += rem * c;        N /= 2;        // Count used to store exponent value        cnt++;    }    return B_Number;} // Driver codeint main(){    int N = 17;    printf("%u", decimalToBinary(N));    return 0;} // This code is contributed by Sania Kumari Gupta (kriSania804)
// Java implementation of the approachimport java.io.*; class GFG{ // Function to return the binary// equivalent of decimal value Nstatic int decimalToBinary(int N){     // To store the binary number    int B_Number = 0;    int cnt = 0;    while (N != 0)    {        int rem = N % 2;        double c = Math.pow(10, cnt);        B_Number += rem * c;        N /= 2;         // Count used to store exponent value        cnt++;    }     return B_Number;} // Driver codepublic static void main (String[] args){         int N = 17;    System.out.println (decimalToBinary(N)); }} // This code is contributed by ajit.
# Python3 implementation of the approach # Function to return the binary# equivalent of decimal value Ndef decimalToBinary(N):         # To store the binary number    B_Number = 0    cnt = 0    while (N != 0):        rem = N % 2        c = pow(10, cnt)        B_Number += rem * c        N //= 2                 # Count used to store exponent value        cnt += 1         return B_Number # Driver codeN = 17print(decimalToBinary(N)) # This code is contributed by# SHUBHAMSINGH10
// C# implementation of the approachusing System; class GFG{     // Function to return the binary// equivalent of decimal value Nstatic int decimalToBinary(int N){     // To store the binary number    int B_Number = 0;    int cnt = 0;    while (N != 0)    {        int rem = N % 2;        int c = (int)Math.Pow(10, cnt);        B_Number += rem * c;        N /= 2;         // Count used to store exponent value        cnt++;    }     return B_Number;} // Driver codestatic public void Main (){    int N = 17;    Console.Write(decimalToBinary(N));}} // This code is contributed by Tushil.
<script> // javascript implementation of the approach // Function to return the binary// equivalent of decimal value Nfunction decimalToBinary(N){     // To store the binary number    var B_Number = 0;    var cnt = 0;    while (N != 0)    {        var rem = N % 2;        var c = Math.pow(10, cnt);        B_Number += rem * c;        N = parseInt(N/2);         // Count used to store exponent value        cnt++;    }    return B_Number;} // Driver codevar N = 17;document.write(decimalToBinary(N)); // This code is contributed by Princi Singh</script>
10001
Time complexity: O(logn) 
Auxiliary Space: O(1) 
Note that this method is similar to the one where we convert Binary to Decimal as discussed in this post.There is yet another method that converts any Decimal Number to its Binary form. The idea is to use bitset.
Below is the implementation of the above approach. 
C++
//C++ program to convert a decimal number//to its binary form. //including header file#include <bits/stdc++.h>using namespace std; //Function to convert a decimal number//to its binary formstring decimalToBinary(int n){    //finding the binary form of the number and    //converting it to string.    string s = bitset<64> (n).to_string();         //Finding the first occurrence of "1"    //to strip off the leading zeroes.    const auto loc1 = s.find('1');         if(loc1 != string::npos)        return s.substr(loc1);         return "0";} //Driver Codeint main(){    int n = 17;         //Function call    cout << decimalToBinary(n);     return 0;} //This code is contributed by yashbeersingh42
10001
Time complexity: O(logn) 
Auxiliary Space: O(1) Another Approach:
C++
Java
Python3
C#
Javascript
// C++ program to convert Decimal to Binary Number#include <bits/stdc++.h>using namespace std; int main(){     // input number    int number = 15;    int n = (int)(log2(number));       // binary output    // using the inbuilt function    cout << "the binary number is : "         << bitset<64>(number).to_string().substr(64 - n                                                  - 1);} // This code is written by phasing17
//To convert Decimal to Binary Number//import java.util.*;    public class Main{        public static void main(String [] args){            //input//            int number =15;                         //output//            System.out.println("the binary number is : "+ Integer.toString(number,2));                         //This code is written by ZEESHAN AHMAD//        }    }
# Python3 program to convert Decimal to Binary Number # input numbernumber = 15 # binary output# using the inbuilt functionprint("the binary number is :", bin(number)[2::]) # This code is written by phasing17
// To convert Decimal to Binary Number//using System;    class GFG{        public static void Main(){            //  input//            int number =15;                          //output//            Console.WriteLine("the binary number is : "+ Convert.ToString(number, 2));        }    } // This code is contributed by code_hunt.
// JavaScript program to convert Decimal to Binary Number // input numbervar number = 15; // binary output// using the inbuilt functionconsole.log("the binary number is :", number.toString(2)); // This code is written by phasing17     
the binary number is : 1111
Time complexity: O(logn) 
Auxiliary Space: O(1) 
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Sam007
jit_t
Mithun Kumar
SoumikMondal
sirraghavgupta
guraseessingh
SHUBHAMSINGH10
yashbeersingh42
mayanktyagi1709
princi singh
surinderdawra388
surindertarika1234
arorakashish0911
codytron
madhav_mohan
phasing17
zeeshan118668
code_hunt
surbhikumaridav
anshitbansal
krisania804
sagartomar9927
base-conversion
binary-representation
MAQ Software
Computer Organization & Architecture
Digital Electronics & Logic Design
GATE CS
Mathematical
MAQ Software
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cache Memory in Computer Organization
Addressing Modes
Logical and Physical Address in Operating System
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization | RISC and CISC
IEEE Standard 754 Floating Point Numbers
Difference between RAM and ROM
Introduction to memory and memory units
Analog to Digital Conversion
Difference between Half adder and full adder