Convert "Floating" to Decimal

Asked

Viewed 3,725 times

3

So does anyone here know how I do to convert 1.01010101 for base 10 in the case this based on 2 "binary" the answer is that in base10 1.3320312510 . I need the logic to handle this case ..

att

#include<stdio.h>
#include<stdlib.h>


int c[18],bcd[20];


//Função de conversão de decimal para binário

void conv_d2b ( unsigned long x,int *c)
{
    int i;
    for(i=0; i<18; i++)
        *(c++)=(x>>i)&0x1;
}





int main()
{
    int escolha;
    double bina ,deci ;
    int k;
    unsigned long int j,x;
    int pos, decimal=0;
    char numb[17];
    int cont=0;

    printf("Conversor de numeros binarios e decimais \n\n");
    printf(" ----------Menu----------\n 1 - Binario para decimal\n 2 - Decimal para binario\n 3 - Decimal fracionario para binario\n 4 - Binario'flutuante' fracionario para Decimal\n 5 - Exit\n\n Opcao: ");
    scanf("%d", &escolha);

    switch(escolha)
    {
    case 1:
        //Conversão de BInarios para Decimal


        printf("Digite um numero Binario qualquer");
        scanf("%s",numb);
        //Processamento da informação
        for (pos=strlen(numb) -1; pos >=0; pos--)
            decimal=decimal + (numb[cont++] - '0')*pow(2,pos);
        //Exibindo a informação
        printf("Seu numero Binario em Decimal eh: %d\n\n", decimal);


        break;

    case 2:


        printf("Digite o numero que deseja converter :");
        scanf("%lu",&x);
        printf("\n\n       \t  Decimal\t      Binario\n");




        printf("   ----  %lu\t    ", x);

        conv_d2b(x,c);
        for(k=17; k>=0; k--)
            printf("%d",c[k]);
        printf("\n\n\r");
        break;

    case 3:

        break;
    case 4:

        break;
    case 5:
        exit(0);
        break;
    default:
        printf("Opcao invalida");
        break;
    }


    return 0;
}

I did something like this

int main()
{
    int  inteiro, binarioInt = 0, i = 1;
    float  binarioFrac = 0, k =0.1f, frac, temp1, binarioTotal, f;

    printf("***** Converter valor FLOAT para BINARIO *******\n");
     printf("***** POR FAVOR UTILIZE PONTO PARA SEPARAR OS NUMEROS *******\n");
    printf("\nEnter com o valor : ");
    scanf("%f",&f);

    //Separando parte inteira
    inteiro = (int)f;

    //Separanto parte fracionada
    frac = f - (int)f;

    //Loop para converter decimal parte inteira em binario
    while(inteiro>0)
    {
        binarioInt = binarioInt + inteiro % 2 * i;
        i = i * 10;
        inteiro = inteiro / 2;
    }

    //Loop para converter fracao em binario
    while(k>0.00000001)
    {
        temp1 = frac *2;
        binarioFrac = binarioFrac+((int)temp1)*k;
        frac = temp1 - (int)temp1;
        k = k / 10;
    }

        //
        binarioTotal = binarioInt +binarioFrac;
        printf(" \nbinary equivalent = %lf\n\n\n\n\n", binarioTotal);
}

3 answers

6

This is easy to solve with basic math:

1.01010101

is the same as

101010101 / 100000000

(just count the houses after the comma)

 Binário       Decimal
 101010101 ÷   314 ÷
 100000000     256
────────────  ─────────────
 1.01010101    1.332031251

In short, just convert normally, and work to decimal.

To simplify, count the houses after the comma, do 2 ^ Número de casas1 and use as a divider:

1.01010101
  └───┬──┘
      └── 8 casas

101010101 = 314
    2 ^ 8 = 256
    │   └───────── 8 casas
    └───────────── base 2, binário. Se fosse decimal, seria 10, hexadecimal 16 etc.

314/256 = 1.332031251

1. I am using a ^ b to indicate a raised to b.


And if it were hexadecimal?

Same thing:

  F,1BC
    └┬┘
     └── 3 casas

  F1BC = 61884
16 ^ 3 =  4096
 │   └───────── 3 casas
 └───────────── base 16

61884/4096 = 15,1083984375


Note: I saw the other question here on the website about showing numbers with decimal places in binary. I think it’s much simpler to use this same technique here in that case too:

Multiply the number by 2 until you have no decimals. Note how many times you multiplied. The number of times is the position of the comma in the binary. (If you want to advance this stage, you can deduce with logarithm, but as it is outside the current question, I will not go into details).

One thing I’ve already mentioned in another issue and applies in this case: regardless of the basis you work on, the math is the same.

0


Sorry it took me so long to post the answer. If someone else could just send it, it would help many. In case the ai program also converts decimal float to binary, binary float to decimal...

/*Trabalho de Calculo numerico  - Converter numero binario para numero decimal*/





#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<math.h>
#define max 30

int fraci[max],inteiro[max];

//Funcoes
void decimalparabinario();
void binarioparadecimal();
float pow();
//Fim Funcoes



int main()
{
    int op;
    float aux,num,f;
    int i,cnum,ch;
    do
    {
        printf("===== Menu ======\n");
        printf("1. Binario para Decimal\n");
        printf("2. Decimal para Binario\n");
        printf("3. Sair\n");
        printf("Digite uma opcao: \n");
        scanf("%d",&op); //
        system("clear"); //Comando utilizado para limpar tela


        switch(op)
        {
        case 1:

            binarioparadecimal();
            system("PAUSE");


            break;
        case 2:
            decimalparabinario();

            system("PAUSE");


            break;
        case 3://Sair do programa
            printf("Saindo..\n");

            break;
        default://Caso não seja nenhuma das anteriores...
            printf("Opcao Invalida\n");
            break;



        }



    }
    while(op != 3);


    system("PAUSE");

    return 0;
}

void decimalparabinario(){

    float numero,f;
    int i,cnum,t;

    printf("Digite um numero Decimal  : ");
    scanf("%f",&numero);
    printf("\n");

    f=numero-(int)numero;

    for(i=0; i<max; i++)
    {
        f=f-(int)f;
        fraci[i]=(int)(f*2);
        f*=2;
    }

    cnum=(int)numero;
    for(i=max-1; i>=0; i--)
    {
        if(cnum%2==0)
        {
            inteiro[i]=0;
        }
        else
            inteiro[i]=1;
        cnum/=2;
    }

    printf("O numero em Binario é igual   = ");
    t=0;

    for(i=0; i<max; i++)
    {
        if(inteiro[i]||t)
        {
            t=1;
            printf("%d",inteiro[i]);
        }
    }
    printf(".");

    for(i=0; i<7; i++)
        printf("%d",fraci[i]);

    printf("\n");



}


void binarioparadecimal()
{
    char num[50];
    int antesDec[50], depoisDec[50];
    int antesDecnum, depoisDecnum, tint=0, l, j=0, k=0;
    float fract=0, floatValue;
    char p = 'd';

    printf("******* Insira o binario para converter  para decimal *********\n");

    //
    printf("Digite o numero binario : ");
    scanf("%s",&num);

    //Separa o inteiro do fracionado

    for(l=0; l<strlen(num); l++)
    {
        if(num[l]=='.')
        {
            p='u';
        }
        else if(p=='d')
        {

            antesDec[l] = (int)num[l]-48;
            k++;
        }
        else
        {
            depoisDec[j] = (int)num[l]-48;
            j++;
        }
    }

    // Armazena o tamanho do inteiro e do fracionario
    antesDecnum = k;
    depoisDecnum= j;

    //Converter parte inteira para decimal
    j=0;
    for(l = antesDecnum-1; l>=0; l--)
    {
        tint = tint + (antesDec[l] *(int) pow(2,j));
        j++;
    }

    //Converter parte fracionaria para decimal
    j = -1;
    for(l = 0; l<depoisDecnum; l++)
    {
        fract = fract + (depoisDec[l]*pow(2,j));
        j--;
    }

    //Juntando as duas partes
    floatValue = tint + fract;
    printf("Numero em decimal é  = %f\n\n\n\n\n",floatValue);


}
float pow(int c, int d)
{
    float pow=1;
    if (d >= 0)
    {
        int i = 1;
        while (i <= d)
        {
            pow = pow * c;
            i++;
        }
    }
    else
    {
        int i = 0;
        while (i > d)
        {
            pow = pow/c;
            i--;
        }
    }
    return pow;
}


// intnum = numero inteiro.
// fracnume = numero fracionario
  • Where possible it is preferable to use double for floating point numbers. All operations with float first convert this value to the type double, for example: float x = 4.2; x *= 2; /* operação feita em double */. In addition the current arithmetic processors are optimized for the type double making operations with types float are slower although the number of bits used is smaller.

  • Great tip, I’ll use next time!!!

0

Dodging a little theory and going right to practice.

#include <string.h>
#include <stdio.h>

int bin2des(unsigned long long bin){
    int x;
    int y;
    char num[18];
    sprintf(num,"%d",bin);
    x = strlen(num);
    y = 1;
    int res;

    while(x--){
        if(num[x] == '-')
            res *= -1;
        else
            res += (num[x]-48)*y;
        y *= 2;
    }

    return res;
}

void main(){
    printf("%i\n",bin2des(101));
}
  • I managed to do here after I send the code in case anyone wants !!!

  • @Matheusfrancisco even though the question is yours, you can post your solution in the answer space. It’s a normal practice, and it’s also a way to help other people with the same problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.