Convert Fractional decimal to binary

Asked

Viewed 17,331 times

4

I’m trying to convert a fractional decimal number to binary.

Let’s go to the example, representing, in binary, the number 0.625.

0,625 x 2 = 1,25 , so the first fraction is 1.

It remains to represent the remaining 0.25 when removing the 1 already represented.

0,25 x 2 = 0,5 , so the second box is 0.

Missing represent the 0,5 .

0,5 x 2 = 1 , so the third house is 1.

0,62510 = 0,1012

For now I made only for whole number..

The code below converts integer to binary.

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

// Função Main
int main() {
 int n;
 int r;
 int i;

 // Lê o número
 printf("Digite o numero: ");
 scanf("%d", &n);

 // Utiliza um número de 32 bits como base para a conversão.
 for(i = 31; i >= 0; i--) {
    // Executa a operação shift right até a
    // última posição da direita para cada bit.
    r = n >> i;

    // Por meio do "e" lógico ele compara se o valor
    // na posição mais à direita é 1 ou 0
    // e imprime na tela até reproduzir o número binário.
    if(r & 1) {
        printf("1");
    } else {
        printf("0");
    }
 }

 printf("\n");

 system("pause");
}

how I treat the fractional part in C?

  • 1

    Binary in what format? It seems to me that what you want is absurdly more complex than this.

  • I want to convert a DECIMAL NUMBER TO BINARY. in case 0.625

  • This says nothing new.

  • In the case of any fractional DECIMAL number for a binary number, I cannot explain in other words. can show with numbers... 20.25 in binary is (10100.01)

  • Binary has no comma, you want to invent it?

  • You want to convert a float to binary is this?

  • In binary the possible digits are 0 and 1. The 2 is not part of. The representation 0.1012 is not a valid representation of a binary number.

  • 1

    How the computer already makes this conversation internally when using type variables double, you can use the computer work and only interpret the bits of the IEEE format.

Show 3 more comments

3 answers

2

how I treat the fractional part in C?

As you demonstrated in the example:

#include <stdio.h>

int main(void) {
    char output[100] = "";
    double x = 0.625;
    while (x) {
        int ch;
        double chk = x * 2;
        if (chk < 1) ch = '0'; else ch = '1';
        sprintf(output, "%s%c", output, ch);
        x = chk;
        if (x >= 1) x -= 1;
    }
    printf("Representacao final: 0.%s\n", output);
    return 0;
}

You can see the function in ideone.

  • yes I liked it , but have to treat all possible cases. example 20,25 also

2


The algorithm you want can be created from the following logic:

  1. Given a number d decimal, for example 12.25d;

  2. Take the whole part of the number and turn it into a binary number b: 12d flipped 1100b;

  3. Add the dot to the binary number: 1100b flipped 1100.b;

  4. Remove the whole part of the decimal number d: 12.25d flipped .25d;

  5. While the remaining decimal number is different from 0, multiply it by 2 and add the whole part (which will be 1 or 0) to its binary number b:

.25d * 2 = 0.50d --> the 0 of 0.50 goes to the binary number b --> 1100.0b. And the decimal number loses the 0 --> .50d. Repeating the process you have to:

.50d * 2 = 1.0

apart from the 1 and adding to the binary number, its final result is

12.25d = 1100.01b

A simplified function that implements the above logic can be defined in C as follows:

void fracaoParaBinario(double fracao) {
    fracao = fracao - (int)fracao; // removendo a parte inteira: 12.25d --> 0.25d

    while (fracao != 0.0) {
        fracao *= 2;
        int resto = (int)fracao;
        fracao -= resto;

        printf("%d", resto);
    }
}

And the complete code, which can be seen by running on Ideone:

# include <stdio.h>

void decimalParaBinario(int decimal) {
    char aux[1000000];
    int i, indice = 0;

    // simples conversão de decimal para binário:
    // divida o decimal por 2 enquanto ele for maior que 0,
    // sempre acumulando o resto das divisões, que compõem o número binário final.
    while (decimal > 0) {
        int resto = decimal % 2;
        aux[indice++] = resto + '0';

        decimal /= 2;
    }

    // o número binário em aux[] está invertido: 12d -->     0011b.
    // abaixo ele será consertado: 12d --> 0011b --> 1100b.
    for (i = 0; indice > 0; indice--, i++) {
        printf("%c", aux[indice - 1]);
    }
}

void fracaoParaBinario(double fracao) {
    fracao = fracao - (int)fracao; // removendo a parte inteira: 12.25d --> 0.25d

    while (fracao != 0.0) {
        fracao *= 2;
        int resto = (int)fracao;
        fracao -= resto;

        printf("%d", resto);
    }
}

void decimalComFracaoParaBinario(double numero) {
    decimalParaBinario((int)numero);
    printf(".");
    fracaoParaBinario(numero);
    printf("\n");
}

int main() {
    double numero;

    numero = 12.25;
    decimalComFracaoParaBinario(numero);

    numero = 62.62510;
    decimalComFracaoParaBinario(numero);

    return 0;
}
  • 1

    I’ll try something.. as soon as I can I put also the result , if anyone wants

-1

Simple method to convert from binary to decimal in calculator

STEP 1: Set how many bits you want to get in the fractional part (F).

STEP 2: Multiply the fractional number by 2 F.

STEP 3: Use decimal to binary calculator conversion. The bits shown are the result of the conversion, with an offset of F bits to the right. I.e., the decimal point is after the digit F (of right to left). Missing digits complete with zeros.

Simple method to convert from decimal to binary in calculator

STEP 1: Write the binary number into the calculator (without the dot decimal).

STEP 2: Use Binary to Decimal Calculator Conversion.

STEP 3: Divide the result by 2 F, where F is the number of bits of the fraction of the number.

Reference

  • I understand your good intentions, but I don’t see where that would help him make the calculation in C, maybe at most it would help him make a real proof.

Browser other questions tagged

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