Sunday, February 7, 2025

Decimal to Binary using Bitwise and operator



Decimal to Binary using Bitwise and operator

#include<stdio.h>
#include<conio.h>
void main()
{
unsigned int mask;
clrscr();
printf("Memory Required : %d butes",sizeof(mask));
getch();
}
Output :
Memory Required : 2 bytes 

Facts :
  1. Output of the Above Program is 2 bytes i.e 16 bits.
  2. Any Integer is represented in 16 bits.
  3. To convert the Decimal Number into Binary , Check First MSB bit of number , if it is 1 then display '1' otherwise display '0'.
  4. We know that for Checking Particular bit we are using Masking Technique using AND(&).
How to Check ?
  1. Firstly 'mask' variable is initialized to 32768 [ 1000 0000 0000 0000]
  2. Given Number 'num' : 10 [ 0000 0000 0000 1010 ]
  3. Do :=  (mask & num )  // ANDing two number's (given variable and  mask variable )
  4. Check whether the Result of ANDing is 0 or not , if Yes Display 0 otherwise Display 1
  5. Right shift mask variable by 1 [ 0100 0000 0000 0000 ]
  6. Now check for Second bit , whether it is 0 or 1
  7. Goto step 3 until 'mask' becomes Zero  [ 0000 0000 0000 0000 ]

Program :

//-----------------------------------------------------
// Program by   : Pritesh A Taral
// Site         : c4learn.blogspot.com
// Program      : Decimal to Binary Conversion
//------------------------------------------------------
#include<stdio.h>
#include<conio.h>
void binary(unsigned int);   // Prototype Declaration
void main()
{
unsigned int num;
printf("Enter Decimal Number : ");
scanf("%u",&num);
binary(num);   // Function Call
getch();
}
//========================================================
void binary(unsigned int num)
{
unsigned int mask=32768;   //mask = [1000 0000 0000 0000]
printf("Binary Eqivalent :  ");
while(mask > 0)
   {
   if((num & mask) == 0 )
         printf("0");
   else
         printf("1");
  mask = mask >> 1 ;  // Right Shift
   }
}
Output :
Enter Decimal Number : 10
Binary Eqivalent :  0000000000001010

Bookmark & Share

Tags / Keywords : | ,

Stumble
Delicious
Technorati
Twitter
Facebook

0 Comments:

Post a Comment

Your Feedback :This is Growing Site and Your Feedback is important for Us to improve the Site performance & Quality of Content.Feel Free to contact and Please Provide Name & Contact Email

 

Learn C Programming Copyright © 2010 LKart Theme is Designed by Lasantha, Free Blogger Templates