Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm assuming that your input data is binary (not text), and that you want to extract chunks of binary data from it. All without making a copy of your input data.</p> <p>You can combine <code>boost::iostreams::basic_array_source</code> and <code>boost::iostreams::stream_buffer</code> (from <a href="http://www.boost.org/doc/libs/1_41_0/libs/iostreams/doc/index.html" rel="noreferrer">Boost.Iostreams</a>) with <code>boost::archive::binary_iarchive</code> (from <a href="http://www.boost.org/doc/libs/1_41_0/libs/serialization/doc/index.html" rel="noreferrer">Boost.Serialization</a>) to be able to use convenient extraction >> operators to read chunks of binary data.</p> <pre><code>#include &lt;stdint.h&gt; #include &lt;iostream&gt; #include &lt;boost/iostreams/device/array.hpp&gt; #include &lt;boost/iostreams/stream.hpp&gt; #include &lt;boost/archive/binary_iarchive.hpp&gt; int main() { uint16_t data[] = {1234, 5678}; char* dataPtr = (char*)&amp;data; typedef boost::iostreams::basic_array_source&lt;char&gt; Device; boost::iostreams::stream_buffer&lt;Device&gt; buffer(dataPtr, sizeof(data)); boost::archive::binary_iarchive archive(buffer, boost::archive::no_header); uint16_t word1, word2; archive &gt;&gt; word1 &gt;&gt; word2; std::cout &lt;&lt; word1 &lt;&lt; "," &lt;&lt; word2 &lt;&lt; std::endl; return 0; } </code></pre> <p>With GCC 4.4.1 on AMD64, it outputs:</p> <blockquote> <p>1234,5678</p> </blockquote> <p>Boost.Serialization is very powerful and knows how to serialize all basic types, strings, and even STL containers. You can easily make your types serializable. See the documentation. Hidden somewhere in the Boost.Serialization sources is an example of a portable binary archive that knows how to perform the proper swapping for your machine's endianness. This might be useful to you as well.</p> <p>If you don't need the fanciness of Boost.Serialization and are happy to read the binary data in an fread()-type fashion, you can use <code>basic_array_source</code> in a simpler way:</p> <pre><code>#include &lt;stdint.h&gt; #include &lt;iostream&gt; #include &lt;boost/iostreams/device/array.hpp&gt; #include &lt;boost/iostreams/stream.hpp&gt; int main() { uint16_t data[] = {1234, 5678}; char* dataPtr = (char*)&amp;data; typedef boost::iostreams::basic_array_source&lt;char&gt; Device; boost::iostreams::stream&lt;Device&gt; stream(dataPtr, sizeof(data)); uint16_t word1, word2; stream.read((char*)&amp;word1, sizeof(word1)); stream.read((char*)&amp;word2, sizeof(word2)); std::cout &lt;&lt; word1 &lt;&lt; "," &lt;&lt; word2 &lt;&lt; std::endl; return 0; } </code></pre> <p>I get the same output with this program.</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