Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.1 kB
7
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <assert.h>

double converte(char *bits, int E, int M) 
{
    int sinal =(bits[0]=='1')?-1:1;
    int bias = pow(2,E-1)-1;
    int i,j,k,exp = 0;
    int expoenteAux = 0, mantissaAux = 0,expoente = 0;
    double mantissa;
    
    for (k=1;k<=E;k++) //contar nº de 1's do expoente
    {
         if (bits[k] =='1') expoenteAux++;      
    }
    for (k=E+1;k<=M+E;k++)//contar nº de 1's da mantissa
    {
         if (bits[k] =='1') mantissaAux++;      
    }
    
    if (expoenteAux == 0 && mantissaAux>0)//desnormalizado
    {   
        mantissa = 0.0;
        for (j=1; j<=E;j++) 
        {
            if (bits[j] =='1') expoente+=E-j;      
        }
        for (i =1+E;i<1+E+M;i++) 
        {
            if (bits[i]=='1') mantissa+=pow(2,-(i-E));    
        }

        return sinal*pow(2,1-bias)*mantissa;
    }
    else if (expoenteAux==E)
    {
        if(mantissaAux>0) return NAN;//not a number
        else return INFINITY;//infinito
    }
    else if (expoenteAux==0 && mantissaAux==0) return 0;
    else //normalizado
    {
        mantissa = 1.0;
        for (j=1;j<=E;j++) 
        {
            if (bits[j] =='1') exp+=pow(2,E-j);      
        }
        for (i =1+E; i<1+E+M;i++) 
        {
            if (bits[i] =='1') mantissa+=pow(2,-(i-E));    
        }
       
        return sinal*pow(2,exp-bias)*mantissa;
    }
    
}

int main() {
    char buf[BUFSIZ];
    int E,M;
    char bits[BUFSIZ][1000];//**??

    int l;
    int i;
    if (scanf("%d", &l)!=0){};
    getchar(); 

    for (i=0;i<l;i++) 
    {       
        assert(fgets(buf, BUFSIZ, stdin) != NULL);
        sscanf(buf,"%d %d %s", &E,&M,bits[i]);
             
    }
    for (i=0;i<l;i++) 
{
    double valor = converte(bits[i],E,M);
    if (isnan(valor)) 
    {
        printf("NaN\n");
    } else if (isinf(valor)) 
    {
        if (bits[i][0]=='0') 
        {
            printf("+Infinity\n");
        } 
        else 
        {
            printf("-Infinity\n");
        }
    } else 
    {
        printf("%lg\n",valor);
    }
}
}
Leave a Comment