WAP to convert decimal to binary number
Objective
Write a C++ program to convert a Decimal number to Binary using Bitwise operators.
Algorithm / Approach
- Read a decimal integer
n. - Run a
forloop starting from 15 down to 0. - Inside the loop, right-shift the bits of
nbycpositions:k = n >> c. - Use the Bitwise AND operator with 1 (
k & 1) to check if the right-most bit is 1 or 0. - Print "1" if true, otherwise print "0".
main.cpp
#include<iostream>
using namespace std;
int main() {
int n, k, c;
cout<<"Enter a Number : ";
cin>>n;
for(c = 15; c>=0; c--) {
k = n>>c;
if(k & 1)
cout<<"1";
else
cout<<"0";
}
cout<< endl;
return 0;
}
Expected Output
Enter a Number : 5 0000000000000101
Explanation of the Program
- Instead of using division and modulo math to calculate the binary representation, this program looks directly at how the computer stores the integer in RAM.
- The Bitwise Right Shift operator (
>>) slides the binary bits of the number to the right. By sliding each bit to the far right position one by one, and using& 1to inspect it, we can visually print the exact binary memory state of the number.
Complexity
Time Complexity
O(1) - Always loops exactly 16 times for a 16-bit visualization.
Space Complexity
O(1)