////////////////////////////////////////////////// // Float_To_Bin.c // //Author: Kamesh Ramani. // //Function: Reads the floating point from a file// //converts to binary and writes back to a file // //Binary format: // // 1. One bit - sign // // 2. Eight bits - Integer part // // 3. Seven bits - Floating part // // 4. Eighteen bits - Total // ////////////////////////////////////////////////// //Library declaration #include #include #include #define SIGN_BITS 1 #define INTEGER_BITS 8 #define FLOAT_BITS 7 void PrintArray(int array[SIGN_BITS + INTEGER_BITS + FLOAT_BITS]); int main(int argc, char *argv[]) { double Float_No = 0.0; int Bin_No[SIGN_BITS + INTEGER_BITS + FLOAT_BITS]; int i = 0; int j = 0; FILE *fp1, *fp2; //Check to see if two arguments are presents if (argc != 3) { printf("Usage: \n"); exit(1); } //Open file to read floating point values if ((fp1=fopen(argv[1],"rt"))=='\0') { printf("Error opening Input file: %s", argv[2]); exit(1); } //Open file to write the binary equivalent if ((fp2=fopen(argv[2],"wt"))=='\0') { printf("Error opeing Output file: %s", argv[3]); exit(1); } for (i = 0; i <= (SIGN_BITS + INTEGER_BITS + FLOAT_BITS)-1; i++) Bin_No[i] = 0; while (!feof(fp1)) { fscanf(fp1, "%lf", &Float_No); fprintf(fp2, "%d. ", j); fprintf(fp2, "%lf => ", Float_No); if (Float_No < 0) { Bin_No[(SIGN_BITS + INTEGER_BITS + FLOAT_BITS) - SIGN_BITS] = 1; Float_No = 0 - Float_No; } if (Float_No >= 1) Bin_No[FLOAT_BITS] = 1; else Bin_No[FLOAT_BITS] = 0; for (i = (FLOAT_BITS+1); i <= (INTEGER_BITS + FLOAT_BITS-1); i++) Bin_No[i] = 0; if (Float_No >= 1) Float_No = Float_No - 1; for(i = (FLOAT_BITS-1); i >= 0; i--) { Float_No = Float_No * 2.0; if (Float_No >= 1) { Float_No = Float_No - 1.0; Bin_No[i] = 1; } else Bin_No[i] = 0; } // Printing x0 fprintf(fp2,"("); for(i = (SIGN_BITS + INTEGER_BITS + FLOAT_BITS) -1; i >= 0; i--) { if ((i==14) || (i==6)) fprintf(fp2," "); fprintf(fp2,"%d",Bin_No[i]); } fprintf(fp2,")"); fprintf(fp2,"\n"); j++; } return 0; } //Print the elements of the array void PrintArray(int array[SIGN_BITS + INTEGER_BITS + FLOAT_BITS]) { int x=0; printf("Printing Array\n"); for (x = (SIGN_BITS + INTEGER_BITS + FLOAT_BITS)-1; x >= 0; x--) { if ((x==14) || (x==6)) printf(" "); printf("%d", array[x]); } printf("\n"); x = 0; printf("Completed Printing\n"); }