/** * Shows how a number is represented as IEEE 754 * * @author Pat Hawks * Course: COMP B13 * Created: Sept 29, 2015 * Source File: ieeefloat.c */ #include #include #include union Float { float value; int ieee; }; long calculateMantissa(int m) { long c = 0; int i = FLT_MANT_DIG; long pos = 5000000000000000; while (--i) { if (m & (1<<(FLT_MANT_DIG-1))) { c += pos; } m <<= 1; pos >>= 1; } if (c) { while (c % 10 == 0) { c /= 10; } } return c; } int main(void) { union Float num; int sign; int mantissa; int exponent; char const* const prompt = "Please enter a floating point decimal number: "; char const* const table = "\n Sign Exponent Mantissa\n Value: %3d 2^%-6d 1.%ld\nEncoded as: %3d %-8d %d\n"; printf("%s", prompt); scanf("%f", &num.value); sign = (num.ieee & INT_MIN)?0:1; mantissa = num.ieee & ((1 << (FLT_MANT_DIG-1)) - 1); exponent = ((num.ieee) >> (FLT_MANT_DIG - 1)) & UCHAR_MAX; printf(table, sign==0?1:-1, exponent-127, calculateMantissa(mantissa), sign, exponent, mantissa); return 0; }