Convert number from decimal to binary C++ program { Method 2 }

Another method to convert number from decimal to binary. To read another method then go to link convert number from decimal to binary { Method 1 }

This program is using bitwise operators & and >>. & gives 1 if both numbers are true otherwise false. See how & operator works.

0 & 0 = 0;

0 & 1 = 0;

1 & 0 = 0;

1 & 1 = 1;


And >> is a right shift and we shift number by one bit and compare it with 1. if result is 1 then print 1 otherwise print 0. Suppose number is 45and 45 in binary system is 101101. Now use bitwise operator.
In 32 bit system 45 will be 00000000000000000000000000101101. Suppose we are taking number in 8 bit so number will be 00101101.

k = n>>7; so  k = 0;
k&1 = 0;

k = n>>6;  so k = 00;
k&1 = 0;

k = n>>5; so k = 001;
k&1 = 1;

k = n>>4;  so k = 0010;
k&1 = 0;
so on..

 
/* C++ program for decimal to binary conversion */
#include<iostream>
using namespace std;
 
int main()
{
 int n,i,bin;
 cout<<"Enter a decimal number: ";
 cin>>n;
 
 cout<<"Binary number is : "<<endl;
 
 for(i=7;i>=0;i--)
 {
  bin=n>>i;
  if(bin&1)
  cout<<"1";
  else
  cout<<"0";
 }
 
 cout<<endl;
 return 0;
 
}

Popular posts from this blog