Below you can find the source code for the famous and always requested Decimal to Binary converter.
I will post 2 versions of it and choose the one you like.
example:
Decimal: 15
Binary: 1111
Please don’t be afraid by the number of lines. The main point of this is the “dec2bin()” function. The rest is for presentation reasons.
Version 1
Here we use the bitwise operator & to convert the decimal. This is the best method!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include <stdio.h> #define BIT_SIZE 32 void dec2bin(char *bin, unsigned long int dec){ int i; for(i=0; i<32; i++) { bin[i] = ((dec&0x80000000) ? '1' : '0'); dec <<= 1; } bin[BIT_SIZE]='\0'; } int main() { unsigned long int num; char bin[BIT_SIZE+1],*t; printf("Enter the decimal: "); scanf("%d",&num); printf("Decimal: %d\n",num); //prints the number given dec2bin(bin,num); t=bin; //do this to avoid typing the leading zeros if you want zeros too just delete the code below while(*t == '0') t++; //////////////////// printf("Binary: %s\n",t); //prints the number in binary format return 0; } |
Version 2
Here is the easiest method to code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #include <stdio.h> #define BIT_SIZE 32 //convert the decimal number into binary void dec2bin(int num,char *bin){ int i; for(i=0;i<BIT_SIZE;i++) //zeroing all the bits bin[i]='0'; //set the bin address at bin[BIN_SIZE] cause the division creates the binary right_to_left bin+=BIT_SIZE-1; while(num>0){ *bin=(num%2)?'1':'0'; num/=2; bin--; } bin[BIT_SIZE]='\0'; } int main(){ unsigned long int num; char bin[BIT_SIZE+1],*t; printf("Enter Decimal: "); scanf("%d",&num); printf("Decimal: %d\n",num); //prints the number given dec2bin(num,bin); //convert the decimal to binary t=bin; //do this to avoid typing the leading zeros if you want zeros too just delete the code below while(*t == '0') t++; //////////////////// printf("Binary: %s\n",t); //prints the binary format of the number return 0; } |
If you have questions for anything posted comment below and we will answer it. Or if you think your code is better than the one posted again post your suggestions and opinions!!!
