Wednesday, 16 May 2012

Write a C program to convert +ve decimal number (integer or floating-point) to a binary number.

#include<stdio.h>
#define bitsize 8
void fracbit(float f);// fn to print bit pattern of fractional part of number
void integbit(int f);// fn to print bit pattern of integral part of number
int main()
{    printf("\n Enter a decimal:\n");
    printf("\n\t[FOR INTEGER PRESS 'I'\t FOR FLOATING-POINT PRESS 'F']\n:");
    char ch;
    scanf("%c",&ch);
    int INT;
    float f;

    switch(ch)
    {    case 'i':
        case 'I':
             printf("\nInput an integer:");
             scanf("%d",&INT);
             printf("\n Bit pattern of %d is:",INT);
             integbit(INT);
             break;
        case 'f':
        case 'F':
             printf("\n Input a floating point number:");
             scanf("%f",&f);
             printf("\n Bit pattern of %.4f is:",f);
             integbit((int)f);
             fracbit(f);
             break;
        default:printf("\n WRONG CHOICE!!ABORTING!!!");
            return 0;
    }
    printf("\n");

    return 0;
}


//fn to print bit pattern of fractional part of decimal
void fracbit(float f)
{    int j=(int)f;
    float f2=f-(float)j;
    int k=0,t,ar[4];
    do
     {   
        f2=f2*2.0;
        t=(int)f2;
        ar[k]=t;
        f2=f2-(float)t;
        k++;
    }while(k<4);
   
    printf(".");
    for(j=0;j<k;j++)
        printf("%d",ar[j]);
}


//fn to print bit pattern of integral part of decimal
void integbit(int I)
{    int ar[bitsize],i=0,j;
    while(I!=0)
    {
        ar[i++]=I%2;
        I=I/2;
    }
    for(j=(bitsize-1);j>=i;j--)
        ar[j]=0;
    for(i=bitsize-1;i>=0;i--)
        printf("%d",ar[i]);
}

0 comments

 
© 2011-2012 ProgrammingBlue
Posts RSS Comments RSS
Back to top