我假设您的输入数据是二进制的(不是文本),并且您想从中提取大块的二进制数据。所有这些都无需复制您的输入数据。
您可以将boost::iostreams::basic_array_source
and boost::iostreams::stream_buffer
(来自Boost.Iostreams)与boost::archive::binary_iarchive
(来自Boost.Serialization)结合起来,以便能够使用方便的提取 >> 运算符来读取二进制数据块。
#include <stdint.h>
#include <iostream>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/archive/binary_iarchive.hpp>
int main()
{
uint16_t data[] = {1234, 5678};
char* dataPtr = (char*)&data;
typedef boost::iostreams::basic_array_source<char> Device;
boost::iostreams::stream_buffer<Device> buffer(dataPtr, sizeof(data));
boost::archive::binary_iarchive archive(buffer, boost::archive::no_header);
uint16_t word1, word2;
archive >> word1 >> word2;
std::cout << word1 << "," << word2 << std::endl;
return 0;
}
使用 AMD64 上的 GCC 4.4.1,它输出:
1234,5678
Boost.Serialization 非常强大,知道如何序列化所有基本类型、字符串,甚至 STL 容器。您可以轻松地使您的类型可序列化。请参阅文档。隐藏在 Boost.Serialization 源代码中的某个地方是一个可移植二进制存档的示例,它知道如何为您的机器的字节序执行正确的交换。这也可能对您有用。
如果您不需要 Boost.Serialization 的花哨并且乐于以 fread() 类型的方式读取二进制数据,则可以basic_array_source
以更简单的方式使用:
#include <stdint.h>
#include <iostream>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
int main()
{
uint16_t data[] = {1234, 5678};
char* dataPtr = (char*)&data;
typedef boost::iostreams::basic_array_source<char> Device;
boost::iostreams::stream<Device> stream(dataPtr, sizeof(data));
uint16_t word1, word2;
stream.read((char*)&word1, sizeof(word1));
stream.read((char*)&word2, sizeof(word2));
std::cout << word1 << "," << word2 << std::endl;
return 0;
}
我用这个程序得到了相同的输出。