Given decimal number, we need to convert it to binary.
We have done it recursive as well as iterative way.
Following is implementation of above algorithm in c language.
/* Algo#51: Description: */ #include#include #include #define MAX 20 void generatebits(int num) { int temp; if(num) { temp = num % 2; //generatebits(num >>= 1); generatebits(num /= 2); printf("%d\t",temp); } } void strrev(char *str) { int len = strlen(str); int s=0,e=len-1; char temp; while(e>=s) { temp = str[s]; str[s] = str[e]; str[e] = temp; s++; e--; } } void dec_to_bin_iterative(int num) { int temp,i=0; char str[MAX]; while(num) { temp = num%2; num/=2; str[i]=temp + '0'; i++; } str[i]='\0'; strrev(str); printf("%s\n",str); } void dec2bin(long i) { char* str; char* p; str = malloc( sizeof(long)*8*sizeof(char) ); p = str; while( i > 0 ) { /* bitwise AND operation with the last bit */ (i & 0x1) ? (*p++='1') : (*p++='0'); /* bit shift to the right, when there are no bits left the value is 0, so the loop ends */ i >>= 1; } while( p-- != str ) /* print out the result backwards */ printf("%c",*p); printf("\n"); free(str); } int main() { int num; num = 6; printf("Recursive Method...\n"); generatebits(num); printf("\nIterative Method...\n"); dec_to_bin_iterative(num); printf("\nBits extraction direct Method...\n"); dec2bin(num); //getch(); return(0); }
Please write comments if you find anything wrong or you want to add something more related to this topic.