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?
Binary in what format? It seems to me that what you want is absurdly more complex than this.
– Maniero
I want to convert a DECIMAL NUMBER TO BINARY. in case 0.625
– Matheus Francisco
This says nothing new.
– Maniero
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)
– Matheus Francisco
Binary has no comma, you want to invent it?
– Maniero
You want to convert a float to binary is this?
– gato
In binary the possible digits are
0
and1
. The2
is not part of. The representation0.1012
is not a valid representation of a binary number.– pmg
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.– pmg