Convert number to binary c++: In the previous article, we have discussed about C++ Program to Convert Binary Number to Decimal Number. Let us learn how to Convert Decimal Number to Binary Number in C++ Program.
Methods to Convert Decimal Numbers to Binary Numbers in C++
Convert decimal to binary c++: In this article, we discuss different methods by which we can convert decimal numbers to binary numbers in c++. The methods that we will discuss today are given below.
- Using arithmetic operator with array
- Using arithmetic operator without the array
- Using bitwise operator
First, discuss the basic intuition behind converting decimal to binary numbers in c++. Suppose a number is 17 and we have to find a binary of 17 then we can do like this:-
17%2!=0 binary=1 17/2=8
8%2==0 binary=01 8/2=4
4%2==0 binary=001 4/2=2
2%2==0 binary=0001 2/2=1
1%2!=0 binary=10001 1/2=0
and we stop. So we get binary of a number like this. Now we will discuss different methods of doing this task.
Method 1-Using arithmetic operator with array
C++ convert decimal to binary: As we see in the example above we do the task in the same manner. First, we check whether the number is divisible by 2 or not. If it is divisible by 2 then we store 0 in the array else we will store 1 in the array. We do the same thing till our number is greater than 0. After that, we will print the elements of the array in the reverse form which will be the answer. Let’s write the code for this.
#include <iostream> using namespace std; void decimalToBinary(int n) { int binaryNum[32],num=n; int i = 0; while (n > 0) { binaryNum[i] = n % 2; n = n / 2; i++; } cout<<num<<" in binary form is "; for (int j = i - 1; j >= 0; j--) { cout << binaryNum[j]; } } int main() { int n = 17; decimalToBinary(n); return 0; }
Output
17 in binary form is 10001
Method 2-Using arithmetic operator without the array
C++ int to binary: We can also do the same task without using the array. Here the idea is the same but instead of an array, we use a variable. Let’s write the code for this.
#include <bits/stdc++.h> using namespace std; int decimalToBinary(int n) { long long binaryNumber = 0; int rem, i = 1, step = 1; while (n!=0) { rem = n%2; n /= 2; binaryNumber += rem*i; i *= 10; } return binaryNumber; } int main() { int n = 17; cout<<n<<" in binary form is "<<decimalToBinary(n); return 0; }
Output
17 in binary form is 10001
Method 3-Using bitwise operator
Decimal to binary c++: We can use bitwise operators to do the above job. Note that bitwise operators work faster than arithmetic operators used above. Let’s write the code for this.
#include <bits/stdc++.h> using namespace std; int decimalToBinary(int n) { cout<<n<<" in binary form is "; int l=log2(n); for (int i = l; i >= 0; i--) { int k = n >> i; if (k & 1) cout << "1"; else cout << "0"; } } int main() { int n = 17; decimalToBinary(n); return 0; }
Output
17 in binary form is 10001
So these are the methods to convert decimal numbers to binary number in c++.