Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to convert decimal to binary number

C Code Example — Loop Programs

ADVERTISEMENT

C Program to convert decimal to binary number

Objective

Write a C program to convert a decimal number to binary using Bitwise Operators.

Algorithm / Approach

  1. Read an integer n.
  2. Start a for loop counting down from 15 to 0 (for a 16-bit binary representation).
  3. Inside the loop, use the Right Shift operator: k = n >> c.
  4. Use the Bitwise AND operator if (k & 1) to check if the right-most bit is a 1 or a 0.
  5. Print "1" or "0" accordingly.
main.c
#include<stdio.h>
int main( ) {
 int n, c, k;
 printf("Enter a number ");
 scanf("%d",&n);
 printf("Binary number of %d =\n",n );
 for(c = 15;c >=0; c--) {
  k = n >> c;
  if(k & 1)
  printf("1");
  else
  printf("0");
 }
 printf("\n");
 return 0;
}

Expected Output

Enter a number 12
Binary number of 12 =
0000000000001100

Explanation of the Program

  • Computers store integers in binary natively. This program extracts that binary representation directly from memory rather than performing mathematical division.
  • The Right Shift operator (&gt;&gt;) slides all the bits of the number to the right by c positions.
  • The Bitwise AND operator (&amp; 1) acts as a mask. It looks exclusively at the very last bit on the right. If that bit is a 1, the result is 1 (True). If it is a 0, the result is 0 (False).

Complexity

Time Complexity O(1) - Loop runs a fixed 16 times.
Space Complexity O(1)
ADVERTISEMENT