Note that there are some explanatory texts on larger screens.

plurals
  1. POBitstream to Float Type Coercion
    text
    copied!<p>I'm having trouble getting the following code to work correctly. Using an online IEEE-754 converter, I wrote out (by hand) to the testData.txt file that is read with the bit string that should signify the floating point number 75.5; the actual cout.write does show that the bit string is as I expect as well. However, when I try to coerce the char* into a float using a union (as I have seen is a typical way to accomplish this conversion) the resulting float is not the number I expect.</p> <pre><code>#include&lt;climits&gt; #include&lt;iostream&gt; #include&lt;fstream&gt; #include&lt;bitset&gt; int main( int, char** ) { std::ifstream inputFile( "testData.txt", std::ios_base::in | std::ios_base::binary ); if( !inputFile ) std::cout &lt;&lt; "Failed to open input file!" &lt;&lt; std::endl; char buffer[ CHAR_BIT * sizeof(float) ]; inputFile.read( buffer, CHAR_BIT * sizeof(float) ); std::cout &lt;&lt; "cout.write of input from file = "; std::cout.write( buffer, CHAR_BIT * sizeof(float) ); std::cout &lt;&lt; std::endl; union { float f; char* c; } fToCharStarUnion; fToCharStarUnion.c = buffer; std::bitset&lt; sizeof(float) * CHAR_BIT &gt; bits( std::string( fToCharStarUnion.c ) ); std::cout &lt;&lt; "fToCharStarUnion.f = " &lt;&lt; fToCharStarUnion.f &lt;&lt; " bits = " &lt;&lt; bits &lt;&lt; std::endl; inputFile.close(); return 0; } </code></pre> <p>The return result of running this is:</p> <pre><code>cout.write of input from file = 01000010100101110000000000000000 fToCharStarUnion.f = -1.61821e+38 bits = 01000010100101110000000000000000 </code></pre> <p>Is there something fundamental I am not doing which will make this work correctly?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload