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.

2
Contributors
2
Replies
6
Views
6 Years
Discussion Span
Last Post by histrungalot
``````#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;
}
``````
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.