/* Name: hw15.c Purpose: Illustrates use of bit-fields and unions to observe floating point representation. Author: Bill Slough */ #include void display_float(unsigned int sign, unsigned int exponent, unsigned int fraction); void display_hex(float value); void demo_display_float(void); void demo_display_hex(void); /* IEEE 754 single precision floating point type */ struct float_t { unsigned int fraction: 23; /* 23-bit mantissa */ unsigned int exponent: 8; /* exponent, excess-127 */ unsigned int sign: 1; /* sign bit: 0 = + 1 = - */ }; union float_view { /* three ways to view a floating point value: */ float f; /* ... as a float */ struct float_t IEEE; /* or three fields, per IEEE */ unsigned int x; /* or 32 bits */ }; int main(void) { /* show each type of conversion */ demo_display_float(); demo_display_hex(); return 0; } /* Given the three components of a single precision floating point value, display it in base 10, "human readable" form */ void display_float(unsigned int sign, unsigned int exponent, unsigned int fraction) { union float_view view; view.IEEE.sign = sign; view.IEEE.exponent = exponent; view.IEEE.fraction = fraction; printf("Floating point value = %12.8f\n", view.f); } /* Display a single precision floating point value as a hexadecimal value */ void display_hex(float value) { union float_view view; view.f = value; printf("sign = %1d, expo = 0x%2.2x, fraction = 0x%6.6x (0x%8.8x)\n", view.IEEE.sign, view.IEEE.exponent, view.IEEE.fraction, view.x); } void demo_display_float(void) { int n; int i; unsigned int sign, exponent, fraction; printf("Demo #1: sign:exponent:fraction -> floating point value\n"); printf(" sign : 0 or 1\n"); printf(" exponent: 2 digit hexadecimal value\n"); printf(" fraction: 6 digit hexadecimal value (0x000000 ... 0x7FFFFF)\n\n"); printf("Enter desired number of test cases: "); scanf("%d", &n); for (i = 0; i < n; i++) { printf("> "); scanf("%x:%x:%x", &sign, &exponent, &fraction); display_float(sign, exponent, fraction); printf("\n"); } printf("\n"); } void demo_display_hex(void) { int i; int n; float value; printf("Demo #2: floating point value -> hexadecimal representation \n"); printf("Enter desired number of test cases: "); scanf("%d", &n); for (i = 0; i < n; i++) { printf("> "); scanf("%f", &value); display_hex(value); printf("\n"); } printf("\n"); }