Skip to main content

C Program to print the decimal number in Binary using bit wise operators.


Algorithm:-

Step 1. Read the decimal number in a variable
             Read num

Step 2. Loop from 31 bit position to 0th bit
             Loop i = 31 to 0

Step 3. Left shift 1 by the [i]th Index
            mask = 1 << i

Step 4. perform  ( & ) operation on the num and mask and print the results
        if (num & mask == 0)
                      print 0
          else
                      print 1

C Program:-

#include<stdio.h> 

/* program for binary reperesentation of
* Decimal Number using bitwise operators
*/ 

int main()
{
   unsigned int decimal,i = 0,mask = 1;

   printf("Enter the decimal number \n");
   scanf("%d",&decimal);

  for (i = 31;i > 0;i--)
  {
     mask = 1 << i;
    (decimal & mask)? printf("1"):printf("0");
  }

  /* for LSB Bit */
  (decimal & 1)? printf("1"):printf("0");
  printf("\n");
  
  return 0;
}
~
~

Output:-

[spatil@localhost ~]$ gcc decimal_bin.c
[spatil@localhost ~]$ ./a.out
Enter the decimal number
7
00000000000000000000000000000111

Comments