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

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