#include "ieee754.h" #include <stdio.h> #include <math.h> //This program convert a floating number to its binary representation (IEEE754) in computer memory int main() { long double f, binaryTotal, binaryFrac = 0.0, frac, fracFractor = 0.1; long int integer, binaryInt = 0; long int p = 0, rem, temp; printf("\nEnter floating number: "); scanf("%Lf", &f); //separate the integer part from the input floating number integer = (int)f; //separate the fractional part from the input floating number frac = f - integer; //loop to convert integer part to binary while (integer != 0) { rem = integer % 2; binaryInt = binaryInt + rem *pow(10, p); integer = integer / 2; p++; } //loop to convert fractional part to binary while (frac != 0) { frac = frac * 2; temp = frac; binaryFrac = binaryFrac + fracFractor * temp; if (temp == 1) frac = frac - temp; fracFractor = fracFractor / 10; } binaryTotal = binaryInt + binaryFrac; printf("binary equivalent = %Lf\n", binaryTotal); } I'm trying to convert floating number to binary representation (64-bit). This code is working but not perfect. For example, when I convert .575 it gives me 0.100100 but when I do the conversion using this website http://www.exploringbinary.com/floating-point-converter/, the right output should be 0.1001001100110011001100110011001100110011001100110011
I am having trouble understanding what makes my code truncate the number. Could anyone help me how to fix it? I appreciate your help.
.:"%.20Lf"will print0.10010011001100110011.double). So it can only print the nearest number, which can be saved in along double. You should save your number into a string.