#include #include //Illustration of unions and bit-fields for "decoding" floating point union number // union: all members occupy the same memory space. // Changing any one member changes all members! { struct //bit fields { unsigned sign : 1; // look at three float fields unsigned expo: 8; unsigned mant: 23; } flt; float floater; // view as float int integer; // view as int unsigned unsign; // view as unsigned int }; void floatFields(number x) { cout << "As a floating point number: sign=" << x.flt.sign << " exponent=" << x.flt.expo << " mantissa=" << x.flt.mant << endl; } int strbin(string word) // pre: word is valid representation of a hex number using lower case // post: returns equivalent integer { int c, j, l; if (word == "") return 0; l = word.length(); c = word[l-1]; if ( '0' <= c && c <= '9') j = c - '0'; else j = c - 'a' + 10; if (l == 1) return j; else return 16 * strbin(word.substr(0,l-1)) + j; } int main() { number x; // number is a union string word; cout << "Number(hex): "; while (cin >> word) { x.unsign = strbin(word); cout << hex << x.unsign << dec << " " << x.integer << " " << x.unsign << " " << x.floater << endl; floatFields(x); cout << "Number(hex): "; } return 0; }