VOOZH about

URL: https://www.geeksforgeeks.org/cpp/cpp-program-for-decimal-to-binary-conversion/

⇱ C++ Program For Decimal To Binary Conversion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C++ Program For Decimal To Binary Conversion

Last Updated : 31 Mar, 2026

Binary Numbers uses only 0 and 1 (base-2), while Decimal Number uses 0 to 9 (base-10). In this article, we will learn to implement a C++ program to convert Decimal numbers to Binary Numbers.

The below diagram shows an example of converting the decimal number 17 to an equivalent binary number.

👁 Image

Decimal to Binary Conversion using Loop

  • Create an array to store the binary representation of size 32, Since the binary representation of an integer can have at most 32 bits.
  • Run a loop till n is greater than 0.
  • Extract the remainder by taking the mod of number using the modulus operator and store the remainder in the array as a binary digit.
  • Update the number by dividing it by 2 in each iteration.
  • Print the array in reverse order.

Code Implementation


Output
1010

Explanation:

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. The 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. The 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. The 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. The new number is 1/2 = 0. 
Step 9: Since the number becomes = 0.
Print the array in reverse order. Therefore the equivalent binary number is 1010.

Complexity Analysis

  • Time complexity: O(log (n))
  • Auxiliary Space: O(1)

Decimal to Binary Conversion using std::bitset

C++ Standard Template Library provides std::bitset class that is used to perform bitwise operations on binary numbers. It can be used to convert Decimal Numbers to Binary and vice versa. In the below C++ program, a bitset of size 4 is created and initialized with 10. Now the bitset binaryRepresentation will store the binary representation of 10.


Output
Binary representation: 1010

Complexity Analysis

  • Time complexity: O(log(n)), where n is the decimal number.
  • Auxiliary Space: O(1)

Refer to the complete article Program for Decimal to Binary Conversion for more methods to convert decimal numbers to binary numbers.

Comment
Article Tags: