Convert Decimal to Binary in C++
In this tutorial, we will learn how to convert a decimal number to binary in C++.
Decimal number is a base 10 number as it ranges from 0 to 9. There are 10 total digit choices we can accommodate in a decimal number.
Whereas a binary number is a base 2 number. It has only two-digit choices, 0 and 1. Every binary number is composed of 0s and 1s.
Theoritcally, we convert decimal to binary as follows:
- Suppose the assumed number is 12.
- Divide 12 by 2. The remainder is 0 and the new number is 6.
- Divide 6 by 2. The new value is 3 and the remainder is 0.
- Divide 3 by 2. The new value is 1 and the remainder is 1.
- Once the value reaches 1, we stop, and the answer is 1100.
The same approach is used while converting decimal to binary in C++.
C++ Code: Convert Decimal to Binary
#include<iostream> using namespace std; void decToBi(int n) { int arr[64]; int i=0; while(n>0) { arr[i]=n%2; n/=2; i++; } for(int j=i-1; j>=0; j--) { cout<<arr[j]; } } int main() { int n = 12; cout<<"Decimal number is: "<<n; int ans = decToBi(n); cout<<"Binary equivalent: "<<ans; return 0; }
Output: Decimal number is: 12 Binary Equivalent: 1100
The explanation to this code is very simple. Have a look if you find the code confusing.
- As the theoretical conversion is explained, the code is very similar to it. The remainder values are used to store the answer.
- An array, arr[], is used to store these remainder values.
- n is divided by 2 each time and the remainder is stored.
- The process is continued till n>0.
- Once the condition fails, the array is printed in reverse order to get the required answer.
Leave a Reply