Program for Decimal to Binary Conversion (original) (raw)

Last Updated : 04 Feb, 2025

Try it on GfG Practice redirect icon

Given a decimal number **n, the task is to convert the given decimal number into an equivalent **binary number.

**Examples:

**Input: n = 12
**Output: “1100”
**Explanation:

binary_conversion_example1

**Input: n = 17
**Output: “10001”
**Explanation:

binary_conversion_example2

Table of Content

[Approach – 1] Division by 2 – O(log n) Time and O(1) Space

The below diagram shows an example of converting the decimal number 17 to an equivalent binary number, by dividing it by 2.

Decimal-to-Binary-Conversion

C++ `

// C++ program to convert a decimal // number to binary number

#include #include using namespace std;

// function to convert decimal to binary string decToBinary(int n) { string bin = "";

while (n > 0) {
    int bit = n%2;
      bin.push_back('0' + bit);
    n /= 2;
}

reverse(bin.begin(), bin.end());
return bin;

}

int main() { int n = 12; cout << decToBinary(n); return 0; }

C

// C program to convert a decimal // number to binary number

#include <stdio.h> #include <string.h>

// Reverse the string void reverse(char *bin, int left, int right) {

while (left < right) {
    char temp = bin[left];
    bin[left] = bin[right];
    bin[right] = temp;
    left++;
    right--;
}

}

// function to convert decimal to binary char* decToBinary(int n) { int index = 0; char* bin = (char*) malloc(32 * sizeof(char));

while (n > 0) {
    int bit = n % 2;
    bin[index++] = '0' + bit;
    n /= 2;
}
bin[index] = '\0';

// Reverse the binary string
reverse(bin, 0, index-1);
  return bin;

}

int main() { int n = 12; char* bin = decToBinary(n);

printf("%s", bin);
return 0;

}

Java

// Java program to convert a decimal // number to binary number

import java.util.*;

class GfG {

// function to convert decimal to binary
static String decToBinary(int n) {
    StringBuilder bin = new StringBuilder();

    while (n > 0) {
        int bit = n % 2;
        bin.append((char) ('0' + bit));
        n /= 2;
    }

    bin.reverse();
    return bin.toString();
}

public static void main(String[] args) {
    int n = 12;
    System.out.println(decToBinary(n));
}

}

Python

Python program to convert a decimal

number to binary number

function to convert decimal to binary

def decToBinary(n): binArr = []

while n > 0:
    bit = n % 2
    binArr.append(str(bit))
    n //= 2

binArr.reverse()
return "".join(binArr)

if name == "main": n = 12 print(decToBinary(n))

C#

// C# program to convert a decimal // number to binary number

using System; using System.Collections.Generic;

class GfG {

// function to convert decimal to binary
static string decToBinary(int n) {
    List<char> bin = new List<char>();

    while (n > 0) {
        int bit = n % 2;
        bin.Add((char)('0' + bit));
        n /= 2;
    }

    bin.Reverse();
    return new string(bin.ToArray());
}

static void Main() {
    int n = 12;
    Console.WriteLine(decToBinary(n));
}

}

JavaScript

// JavaScript program to convert a decimal // number to binary number

// Function to convert decimal to binary function decToBinary(n) { let bin = [];

while (n > 0) {
    let bit = n % 2;
    bin.push(String(bit));
    n = Math.floor(n / 2);
}

bin.reverse();
return bin.join("");

}

// Driver Code let n = 12; console.log(decToBinary(n));

`

[Approach – 2] Using Head Recursion – O(log n) Time and O(log n) Space

The idea is same as the previous approach, but we will use recursion to generate the binary equivalent number.

C++ `

// C++ program to convert a decimal // number to binary number

#include #include using namespace std;

// Recursive function to convert decimal to binary void decToBinaryRec(int n, string &bin) { // Base Case if (n==0) return;

  // Recur for smaller bits.
  decToBinaryRec(n/2, bin);

  // Add MSB of current number to the binary string
  bin.push_back(n%2 + '0');

}

// Function to convert decimal to binary string decToBinary(int n) { if (n == 0) return "0";

string bin = "";
  decToBinaryRec(n, bin);
  return bin;

}

int main() { int n = 12; cout << decToBinary(n); return 0; }

Java

// Java program to convert a decimal // number to binary number

class GfG {

// Recursive function to convert decimal to binary
static void decToBinaryRec(int n, StringBuilder bin) {
    // Base Case
    if (n == 0)
        return;

    // Recur for smaller bits.
    decToBinaryRec(n / 2, bin);

    // Add MSB of current number to the binary string
    bin.append(n % 2);
}

// Function to convert decimal to binary
static String decToBinary(int n) {
    if (n == 0)
        return "0";

    StringBuilder bin = new StringBuilder();
    decToBinaryRec(n, bin);
    return bin.toString();
}

public static void main(String[] args) {
    int n = 12;
    System.out.println(decToBinary(n));
}

}

Python

Python program to convert a decimal

number to binary number

Recursive function to convert decimal to binary

def decToBinaryRec(n, binArr): # Base Case if n == 0: return

# Recur for smaller bits.
decToBinaryRec(n // 2, binArr)

# Add MSB of current number to the binary list
binArr.append(str(n % 2))

Function to convert decimal to binary

def decToBinary(n): if n == 0: return "0"

binArr = []
decToBinaryRec(n, binArr)
return "".join(binArr)

if name == "main": n = 12 print(decToBinary(n))

C#

// C# program to convert a decimal // number to binary number

using System; using System.Text;

class GfG {

// Recursive function to convert decimal to binary
static void decToBinaryRec(int n, StringBuilder bin) {
    // Base Case
    if (n == 0) 
        return;

    // Recur for smaller bits.
    decToBinaryRec(n / 2, bin);

    // Add MSB of current number to the binary string
    bin.Append(n % 2);
}

// Function to convert decimal to binary
static string decToBinary(int n) {
    if (n == 0) 
        return "0";

    StringBuilder bin = new StringBuilder();
    decToBinaryRec(n, bin);
    return bin.ToString();
}

static void Main() {
    int n = 12;
    Console.WriteLine(decToBinary(n));
}

}

JavaScript

// JavaScript program to convert a decimal // number to binary number

// Recursive function to convert decimal to binary function decToBinaryRec(n, bin) { // Base Case if (n === 0) return;

// Recur for smaller bits.
decToBinaryRec(Math.floor(n / 2), bin);

// Add MSB of current number to the binary string
bin.push(n % 2);

}

// Function to convert decimal to binary function decToBinary(n) { if (n === 0) return "0";

let bin = [];
decToBinaryRec(n, bin);
return bin.join("");

}

// Driver code let n = 12; console.log(decToBinary(n));

`

[Approach – 3] Using BitWise Operators – O(log n) Time and O(1) Space

We can use bitwise operators to do the above job.

Note that bitwise operators work faster than arithmetic operators used above.

C++ `

// C++ program to convert a decimal number to binary number // using bitwise operations

#include #include using namespace std;

// Function to convert decimal to binary string decToBinary(int n) {

  // String to store the binary representation
string bin = ""; 

while (n > 0) {
  
    // Finding (n % 2) using bitwise AND operator
    // (n & 1) gives the least significant bit (LSB)
    int bit = n & 1;
    bin.push_back('0' + bit);
      
    // Right shift n by 1 (equivalent to n = n / 2)
    // This removes the least significant bit (LSB)
    n = n >> 1;
}
  
reverse(bin.begin(), bin.end());
return bin;

}

int main() { int n = 12; cout << decToBinary(n); return 0; }

C

// C program to convert a decimal number to binary number // using bitwise operations

#include <stdio.h> #include <string.h>

// Function to Reverse the string void reverse(char *bin, int left, int right) {

while (left < right) {
    char temp = bin[left];
    bin[left] = bin[right];
    bin[right] = temp;
    left++;
    right--;
}

}

// function to convert decimal to binary char* decToBinary(int n) { int index = 0; char* bin = (char*) malloc(32 * sizeof(char));

while (n > 0) {
  
      // Finding (n % 2) using bitwise AND operator
    // (n & 1) gives the least significant bit (LSB)
    int bit = n & 1;
    bin[index++] = '0' + bit;
  
      // Right shift n by 1 (equivalent to n = n / 2)
    // This removes the least significant bit (LSB)
    n = n >> 1;
}
bin[index] = '\0';

// Reverse the binary string
reverse(bin, 0, index-1);
  return bin;

}

int main() { int n = 12; char* bin = decToBinary(n);

printf("%s", bin);
return 0;

}

Java

// Java program to convert a decimal number to binary number // using bitwise operations

import java.util.*;

class GfG {

// Function to convert decimal to binary
static String decToBinary(int n) {
  
    // String to store the binary representation
    StringBuilder bin = new StringBuilder();

    while (n > 0) {

        // Finding (n % 2) using bitwise AND operator
        // (n & 1) gives the least significant bit (LSB)
        int bit = n & 1;
        bin.append(bit);

        // Right shift n by 1 (equivalent to n = n / 2)
        // This removes the least significant bit (LSB)
        n = n >> 1;
    }

    return bin.reverse().toString();
}

public static void main(String[] args) {
    int n = 12;
    System.out.println(decToBinary(n));
}

}

Python

Python program to convert a decimal number to binary number

using bitwise operations

Function to convert decimal to binary

def decToBinary(n):

# String to store the binary representation
bin = ""

while n > 0:

    # Finding (n % 2) using bitwise AND operator
    # (n & 1) gives the least significant bit (LSB)
    bit = n & 1
    bin += str(bit)

    # Right shift n by 1 (equivalent to n = n // 2)
    # This removes the least significant bit (LSB)
    n = n >> 1

return bin[::-1]

if name == "main": n = 12 print(decToBinary(n))

C#

// C# program to convert a decimal number to binary number // using bitwise operations

using System; using System.Text;

class GfG {

// Function to convert decimal to binary
static string decToBinary(int n) {
  
    // String to store the binary representation
    StringBuilder bin = new StringBuilder();

    while (n > 0) {

        // Finding (n % 2) using bitwise AND operator
        // (n & 1) gives the least significant bit (LSB)
        int bit = n & 1;
        bin.Append(bit);

        // Right shift n by 1 (equivalent to n = n / 2)
        // This removes the least significant bit (LSB)
        n = n >> 1;
    }

    char[] arr = bin.ToString().ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
}

static void Main() {
    int n = 12;
    Console.WriteLine(decToBinary(n));
}

}

JavaScript

// JavaScript program to convert a decimal number to binary number // using bitwise operations

// Function to convert decimal to binary function decToBinary(n) {

// String to store the binary representation
let bin = "";

while (n > 0) {

    // Finding (n % 2) using bitwise AND operator
    // (n & 1) gives the least significant bit (LSB)
    let bit = n & 1;
    bin += bit;

    // Right shift n by 1 (equivalent to n = Math.floor(n / 2))
    // This removes the least significant bit (LSB)
    n = n >> 1;
}

return bin.split("").reverse().join("");

}

// Driver code let n = 12; console.log(decToBinary(n));

`

[Approach – 4] Using Built-In Methods

The idea is to use **built-in functions to convert a decimal number to its **binary representation.

C++ `

// C++ program to convert Decimal to Binary Number // Using the inbuilt function

#include <bits/stdc++.h> using namespace std;

// Function to convert decimal to binary string decToBinary(int n) { int len = (int)(log2(n));

// Store in bitset to get the binary representation, 
  // then convert it to string
  // and finally remove the prefix zeroes
return bitset<64>(n).to_string().substr(64 - len - 1);

}

int main() { int n = 12; cout << decToBinary(n); return 0; }

Java

// Java program to convert Decimal to Binary Number // Using the inbuilt function

class GfG {

// Function to convert decimal to binary
static String decToBinary(int n) {
    int len = (int)(Math.log(n) / Math.log(2));

    // Convert to binary string and remove leading zeros
    return String.format("%s", Integer.toBinaryString(n));
}

public static void main(String[] args) {
    int n = 12;
    System.out.println(decToBinary(n));
}

}

Python

Python program to convert Decimal to Binary Number

Using the inbuilt function

import math

Function to convert decimal to binary

def decToBinary(n): return bin(n)[2::]

if name == "main": n = 12 print(decToBinary(n))

C#

// C# program to convert Decimal to Binary Number // Using the inbuilt function

using System;

class GfG {

// Function to convert decimal to binary
static string decToBinary(int n) {
    return Convert.ToString(n, 2);
}

static void Main() {
    int n = 12;
    Console.WriteLine(decToBinary(n));
}

}

JavaScript

// JavaScript program to convert Decimal to Binary Number // Using the inbuilt function

// Function to convert decimal to binary function decToBinary(n) { return n.toString(2); }

// Driver Code let n = 12; console.log(decToBinary(n));

`