facebook like button

10 April, 2011

program 32: binary conversion

The need:
     This program converts a given decimal integer to equivalent binary number.

The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int i=0,j,k,l,m;
    char str1[50],str2[50];
    printf("Enter a decimal integer => ");
    scanf("%d",&k);
    m=k;                   //storing k for further use
    while(k>0){            //while loop for storing remainder
       if(k%2==0)          //of each division by 2 in a string
       str1[i]='0';        //variable str1
       else
       str1[i]='1';
       k/=2;
       i++;
    }
    str1[i]='\0';
    l=i;
    j=i-1;
    for(i=0;j>=0;i++,j--)
      str2[j]= str1[i];
    printf("The binary equivalent of %d is => ",m);
    for(j=0;j<l;j++)
    putchar(str2[j]);
    getchar();
}
--------------------------------------------
 
The approach:
    You people are supposed to know what binary numbers are and how we can convert a decimal number to corresponding binary number on paper. That same division method is used in this program. First a number is scanned in variable k. During run of the program value of k will be changed so I have backed-up the value of k in another variable m. After while loop variable str1 will be containing all the remainders. But binary equivalent is reverse of remainders. In previous program I demonstrated how to reverse a string without using another string variable but here I am using another string variable str2 to get the reversed string in it.

4 comments:

  1. Here is an alternative method, without using string to store the remainder. It's sort of better way of doing.
    C program to convert decimal number into binary

    ReplyDelete
  2. good to see this. But your program wont convert decimal numbers which have binary conversion more than 10 binary digits while this program will. I also have further extension of this program using which you can convert up to 2000digit decimal integer. :)

    ReplyDelete
  3. I have written this code and it seems to work pretty well

    #include
    int main()
    {
    int n,r=0,sum[100],j;
    scanf("%d",&n);
    int i=0;
    while(n!=0)
    {
    r=n%2;
    sum[i]=r;
    n=n/2;
    i++;
    }
    //sum[i+1]="\0";
    printf("digits of number in binary is \n");
    for(j=i-1;j>=0;j--)
    printf("%d",sum[j]);
    printf("\n");
    return 0;
    }

    ReplyDelete
    Replies
    1. Good. You are doing the same with integer array what I have done with character array. the only difference is, you didn't store the reversed binary value, just printed the reverse.

      Delete

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply