#include #include double pow(int); int computeFloat(int, int, double); double reconstructFloat(int, int, int, int, int); void floatMult(int, int, int, int, int, int, int, int); int main(int argc, char** arv) { printf("Number\t\tSign\tExp\tMantissa\tReconstructed\n\n"); int i = 0; int expSize = 4; int mantSize = 5; for (i = -15; i < 16; i++) { if (i != 0) { printf("%f:\t", (double)i); computeFloat(expSize, mantSize, (double) i); } } floatMult(expSize, mantSize, 1, 11, 28, 0, 9, 0); } int computeFloat(int expSize, int mantissaSize, double number) { double normaliser = (double) (1 << (expSize - 1)); double scale; double exp; double tempNumber; int i; int reconSign; int reconExp; int reconMantissa; if (number < 0.0) { reconSign = 1; number = -1 * number; } else { reconSign = 0; } /* Cheap way to get the exponent. You wont need to do this in HW */ exp = computeExp(number); /* Normalise this so is 1.something */ if (exp < 0) /* we want it to round the right way...*/ number = number /= pow((int)exp - 1); else number = number /= pow((int)exp); number = number - 1.0; tempNumber = number; /* This litte bit computes the mantissa */ scale = 0.5; reconMantissa = 0; for (i = 0; i < mantissaSize; i++) { reconMantissa = reconMantissa << 1; if (number >= scale) { reconMantissa += 1; number -= scale; } scale /= 2; } /* Print out some stuff about the number we tried */ printf("%d\t%d\t%d\t\t", reconSign, reconExp, reconMantissa); printf("%f\n", reconstructFloat(expSize, mantissaSize, reconSign, reconExp, reconMantissa)); } double reconstructFloat(int expSize, int mantSize, int sign, int exp, int mant) { double reconNumber; if (sign) reconNumber = -1.0; else reconNumber = 1.0; exp -= 1 << (expSize - 1); reconNumber *= pow(exp); reconNumber *= 1.0 + ((double)mant) / pow(mantSize); return(reconNumber); } double pow(int x) { double retVal = 1.0; int i; if (x > 0) { for (i = 0; i < x; i++) retVal *= 2.0; } else { for (i = 0; i > x; i--) retVal /= 2.0; } return(retVal); } /* Computes the exponent of a POSITIVE double */ int computeExp(double num) { int counter; if (num > 1.0) { for (counter = 0; num > 2.0; count++) num /= 2.0; } else { for (counter = 0; num < 1.0; count--) num *= 2.0; } }