Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You are translating the ASCII into bits using the constructor of <code>bitset</code>. That causes your decoded bits to be in the <code>bitset</code> object rather than the <code>union</code>. To get raw bits out of a bitset, use the <code>to_ulong</code> method:</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[ sizeof(unsigned long)/sizeof(float) ]; unsigned long l; } funion; funion.l = std::bitset&lt;32&gt;( std::string( buffer ) ).to_ulong(); std::cout &lt;&lt; "funion.f = " &lt;&lt; funion.f[0] &lt;&lt; " bits = " &lt;&lt; std::hex &lt;&lt;funion.l &lt;&lt; std::endl; inputFile.close(); return 0; } </code></pre> <p>This generally assumes that your FPU operates with the same endianness as the integer part of your CPU, and that <code>sizeof(long) &gt;= sizeof(float)</code>… less guaranteed for <code>double</code>, and indeed the trick is harder to make portable for 32-bit machines with 64-bit FPUs.</p> <p><strong>Edit:</strong> now that I've made the members of the union equal sized, I see that this code is sensitive to endianness. The decoded <code>float</code> will be in the last element of the array on a big-endian machine, first element on little-endian. :v( . Maybe the best approach would be to attempt to give the integer member of the union exactly as many bits as the FP member, and perform a narrowing cast after getting <code>to_ulong</code>. Very difficult to maintain the standard of portability you seemed to be shooting for in the original code.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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