Convert Fractional Decimal to Binary

3

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 fractional house 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 house is 0.

  

0.5 x 2 = 1, so the third house is 1.

     

0.62510 = 0.1012

For the moment I've done only for integer ..

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 do I treat the fractional part in C?

    
asked by anonymous 24.03.2016 / 16:02

3 answers

2

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

  • Given a number d decimal, for example 12.25d ;

  • Take the integer part of the number and transform it into a binary number b : 12d 1100b ;

  • Add the point to the binary number: 1100b turns 1100.b ;

  • Remove the integer part of the decimal number d : 12.25d .25d ;

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

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

    .50d * 2 = 1.0
    

    By taking 1 and adding it to the binary number, its end 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 full code, which can be seen running at 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;
    }
    
        
    24.03.2016 / 17:27
    2
      

    How do I treat the fractional part in C?

    As you showed 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 watch work on ideone .

        
    24.03.2016 / 17:23
    -1

    Simple method to convert from binary to decimal in the calculator

      

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

         

    STEP 2: Multiply the fractional number by 2 ^ F.

         

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

    Simple method to convert from decimal to binary in calculator

      

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

         

    STEP 2: Use the binary to decimal conversion of the calculator.

         

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

    Reference a>

        
    16.02.2018 / 18:23