C++float assigned to unsigned long y

I have to write separate C++ expression for:

1) extract the 8-bit exponent field to the low order bits of y, and subtract the 127 bias.
2) isolate the mantissa field in the lower order bits of y, and insert the implicit leading 1.

I am not expecting anyone to provide me with the answers, I only want some tips on how to go about understanding how to do this.

Reference: http://en.wikipedia.org/wiki/Single-precision_floating-point_format

#include <iostream>
// Needed for the hex, showbase, setfill and setw
#include <iomanip>
using namespace std;
int main(){
 // Set the floating point number
 float floatVal(-1);
 // Want the integer form of what the float looks like, not the integer
 // part of the float.
 unsigned int intValOfFloat(*reinterpret_cast<unsigned int*>(&floatVal));
 // Debug
 cout << showbase << setfill('0') << setw(8) << hex << intValOfFloat << endl;

 //
 // Now that the floating point number is an integer, extract the bits 
 // you want based on the picture below 
 //     ---------------------------------------------------------------------
 //    | s | e e e e e e e e | m m m m m m m m m m m m m m m m m m m m m m m |
 //     ---------------------------------------------------------------------
 // s = sign bit
 // e = exponent bits
 // m = mantissa bits

 // The output from the cout above is 0xbf800000.  
 // Does that make sense given that the floating point number was -1?
 // Try another number that is a power to 2 to make sure you understand.

 return 0;
}
Use a union, it's cleaner.
#include <iostream>
// Needed for the hex, showbase, setfill and setw
#include <iomanip>
using namespace std;
int main(){
  // ----------------------------------------------
  // I like this better.  It's cleaner no pointers.
  union {
    float        floatVal;
    unsigned int intVal;
  } x;

  x.floatVal = -1;
  // Want the integer form of what the float looks like, not the integer
  // part of the float.
  // Debug
  cout << showbase << setfill('0') << setw(8) << hex << x.intVal << endl;

  //
  // Now that the floating point number is an integer, extract the bits 
  // you want based on the picture below 
  //     ---------------------------------------------------------------------
  //    | s | e e e e e e e e | m m m m m m m m m m m m m m m m m m m m m m m |
  //     ---------------------------------------------------------------------
  // s = sign bit
  // e = exponent bits
  // m = mantissa bits

  // The output from the cout above is 0xbf800000.  
  // Does that make sense given that the floating point number was -1?
  // Try another number that is a power to 2 to make sure you understand.

  return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.